highlighting a section of a plot

88 views (last 30 days)
Miguel De Leon
Miguel De Leon on 17 Aug 2022
Answered: Star Strider on 17 Aug 2022
I am trying to highlight within this plot a subset of variables based on my x-axis. For example, I want highlight a section of this plot that is between 1730 and 1745. I have looked through mathworks and so far have the code below. I am not sure about "y = sin(x)" or the portion I have marked "[not sure what to put here].
x = linspace(500, 4000)
y = sin(x)
ptchidx = (t >= 1730) & (t <= 1745);
figure(1)
plot(x, y)
hold on
patch([t(ptchidx) fliplr(t(ptchidx))], [y(ptchidx) zeros(size(y(ptchidx)))], [not sure what to put here], 'FaceAlpha',0.3, 'EdgeColor','none')
hold off
grid

Answers (2)

Kevin Holly
Kevin Holly on 17 Aug 2022
Here is another approach using area function.
x = linspace(500, 4000);
y = sin(x);
Note, this is only one point, so I illustrated example by highlighting between 1700 and 1800
x(x>1730&x<1745)
ans = 1.7374e+03
figure(1)
plot(x, y)
hold on
area(x(x>1700&x<1800),y(x>1700&x<1800))
z = ones(size(y));
figure(2)
plot(x, y)
hold on
area(x(x>1700&x<1800),z(x>1700&x<1800),"FaceColor","r","FaceAlpha",0.5)
area(x(x>1700&x<1800),-z(x>1700&x<1800),"FaceColor","r","FaceAlpha",0.5)

Star Strider
Star Strider on 17 Aug 2022
The ‘x’ vector needs to have more elements in order to provide the necessary resolution to draw the patch object correctly.
The proper argument for ‘[not sure what to put here]’ is the RGB triplet of your choice —
x = linspace(500, 4000, 1E+4); % Increase Resolution
y = sin(x);
t = x;
ptchidx = (t >= 1730) & (t <= 1745);
figure(1)
plot(x, y)
hold on
patch([t(ptchidx) fliplr(t(ptchidx))], [y(ptchidx) zeros(size(y(ptchidx)))], [0.9 0.7 0.5], 'FaceAlpha',0.3, 'EdgeColor','none')
hold off
grid
xline([1730 1745], '-r', 'LineWidth',1.25) % <— Added
axis([1700 1800 -1 1])
I added the xline call to define the region of interest since the 'FaceAlpha' value otherwise makes it difficult to see easily.
The rest of the code is essentially as you posted it.
.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by