Add background color for some values in a plot of two two variables

Hi everyone. I have two variables av1 and av2. Each variables have 114 data points. I want to draw it in same figure but at same time and point I also want to calculate p value from ttest between av1 and av2. So if the significance difference is less then 0.05 at that data point it should draw a background colour. I attached the figure.

1 Comment

Remember to mark the question as answered or post follow-up comments.

Sign in to comment.

Answers (1)

You can plot a bar graph and then set the FaceAlpha to less than 1.
x = [0 1 2 2 3 4 4 6 7 7];
y = [1 2 2 3 4.5 4.5 6 7];
p = [2.15e-12 2.72e-11 2.397e-10 0.0600 5.613e-09 1.803e-08 4.831e-08...
8.945e-08 1.874e-07 2.894e-07];
plot(x,'b')
hold on;
plot(y, 'k')
ax = gca; %Get axis size info
ylimVals = ax.YLim; %Y limits
scaleFact = max(ylimVals);
b1 = bar(scaleFact*(p < 0.05),'b'); %plot blue bar graph
b1.FaceAlpha = 0.5; %Set transparency to 50%
b1.EdgeAlpha = 0; %Maybe you want no outline on the bar
ylim(ylimVals); %Set ylim correctly
uistack(b1, 'bottom') %Move background below other elements

5 Comments

@Ben Thank you. These are the two files. Each file contain 114 data points. Actually i give you that figure as example. I want to plot these two data in one figure. Then ttest will be applied on both data, so when the p value will be less then 0.05, at that point in same figure the background color will be appear same as above figure.
Maybe you could show your code for calculating the values? I don't have any experience with ttest, so maybe you could also share a logical index showing at which of the 114 samples you want the background, if you don't want to share the code that makes the data.
@Ben Ok I also uploaded the file which contain p values on 114 points. So just need to draw back ground colour on the data point where p<0.05.
x = af; % first data file
y = bf; % second data file
plot(x, 'b')
hold on
plot(y,'k')
hold on
for i = 1:length(x)
if p(i) < 0.05
% i need to do something here to draw background color on data point when p<0.05.
end
end
I've edited my answer and tested the code locally with your data and think it does what you want.
I think the key understanding here is that you don't need to loop through p. MATLAB allows vector calculations, so you can check every cell in p at once.
out = p < 0.05;
Out will be a logical index (that is, 1 where p < 0.05, 0 otherwise) with the same length as p. You can then plot the logical index with a scaling factor to get the background at a consistent height.
@Muhammad Usman Please mark the question as answered if it has been answered.

Sign in to comment.

Categories

Find more on Creating, Deleting, and Querying Graphics Objects in Help Center and File Exchange

Asked:

on 14 Sep 2022

Commented:

Ben
on 23 Sep 2022

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!