Use "fill" in a datetime/value plot to color the background
13 views (last 30 days)
Show older comments
Hello, i want to plot a value ove time series, where the time is stored in the matlab specific time format. Furthermore i want to color the background of this plot to symbolise different states of the represented machine. How can i adapt the fill command to work with these conditions ? Its important that the axes changes the displayed time when i zoom into the figure.
Thanks in advance
%the plot
t = datetime(2014,6,28) + caldays(1:10);
y = rand(1,10);
plot(t,y);
%fill background:
%black between Jun30 and Jun31, between Juli4 and Juli5
%red for the rest
0 Comments
Accepted Answer
Brendan Hamm
on 14 Sep 2016
Edited: Eric Sargent
on 9 Dec 2020
You can use the fill function to achieve this.
To do so, first generate the data:
t = datetime(2014,6,28) + caldays(1:10);
y = rand(1,10);
Generate the limits for the black patches:
x1 = datetime(2014,6,30);
x2 = datetime(2014,6,31);
x3 = datetime(2014,7,4);
x4 = datetime(2014,7,5);
Generate some y-values for the black areas
y1 = [0 1 1 0];
Create the axes and create the black areas.
ax = axes;
fill([x1 x1 x2 x2],y1,'k');
hold on;
fill([x3 x3 x4 x4],y1,'k');
Plot the line such that it's rendered over the black areas.
plot(t,y,'y','LineWidth',2);
hold off;
Turn the axes color to red so that it's red for all other areas (per your requirement).
ax.Color = 'r';
The axes also show a changed display for the time.
2 Comments
KAE
on 15 May 2020
This does not work for me in R2019b. The yellow line and the red patch have very diferent x-values.
More Answers (0)
See Also
Categories
Find more on Line Plots in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!