How to color some region of plot?

410 vues (au cours des 30 derniers jours)
Enrica Brunetti
Enrica Brunetti le 25 Août 2019
Modifié(e) : Afiq Azaibi le 17 Mar 2023
If I have this plot
y = [70, 72, 60, 66, 60, 57, 59, 58, 60, 73, 72, 73, 73, 72, 52, 72, 77, 59, 49, 66];
x = [1: 20];
what function can I use to color some region of plot, when for example y(i) > 70?

Réponse acceptée

Image Analyst
Image Analyst le 25 Août 2019
Modifié(e) : Image Analyst le 25 Août 2019
Try this,using patch():
% Plot original data.
y = [70, 72, 60, 66, 60, 57, 59, 58, 60, 73, 72, 73, 73, 72, 52, 72, 77, 59, 49, 66];
x = [1: 20];
plot(x, y, 'b*-');
grid on;
hold on;
% Make patch of transparent color.
yl = ylim
xl = xlim
xBox = [xl(1), xl(1), xl(2), xl(2), xl(1)]
yBox = [70, yl(2), yl(2), 70, 70]
patch(xBox, yBox, 'black', 'FaceColor', 'green', 'FaceAlpha', 0.1);
hold off;
  4 commentaires
Enrica Brunetti
Enrica Brunetti le 21 Sep 2019
But if I want to color with the use of the same code, the region for y(i)< 60?
Afiq Azaibi
Afiq Azaibi le 17 Mar 2023
Modifié(e) : Afiq Azaibi le 17 Mar 2023
In addition to Image Analyst's solution, starting in R2023a you can use the xregion and yregion functions.
y = [70, 72, 60, 66, 60, 57, 59, 58, 60, 73, 72, 73, 73, 72, 52, 72, 77, 59, 49, 66];
x = [1: 20];
plot(x, y, 'b*-');
yregion(70,80,"FaceColor", 'g'); % Note, 80 is the end point so if you pan past 80, the region will stop.
yregion(45, 70, "FaceColor", 'r');
You can also set the EdgeColor properties to emphasize the edges but the default EdgeColor is 'none'.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Lighting, Transparency, and Shading dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by