How to fill the area between two curves with discrete data and with a condition (y<0 & y>0)?
4 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I have a vector containing the values I want to plot in y (data.mat).
In x, I have years ranging from 1979 to 2018.
The data range between negative and positive values.
I want to shade the area between y = 0 and the data when data < 0 with a specific color, and I want to shade the area between y = 0 and data > 0 with a different color.
Since my data is discrete, I cannot fill exactly the region below/above zero since the shift from negative to positive (or vice versa) does not necessarily occur on exact years.
I tried to alleviate this issue by adding 0 to my data at the location where the data was the opposite sign (see commented code for this try). It works better, but the fit is still not exact.
How should I do this to have a region that exactly matches my curve?
Here is what I have tried:
% Data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
load('data.mat');
year = [1979:1:2018]; %x axis
y0 = zeros(length(year),1); % y = 0 vector
index1 = find(data<0); %index for negative values
%% Figure %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure(1)
grid on;hold on;
area(year(index),data(index),'FaceColor', [ 0.7500 0.7500 0.7500]);
%{
%Test (better but still not working)
index2 = find(data>0); %index for positive values
data2 = data;
data2(index2) = 0;
Y = [y0,data2];
area(year,Y,'FaceColor', [0.9000 0.9000 0.9000]);
%}
plt1 = yline(0,'LineWidth',2, 'Color', 'black','LineStyle','--');
plt2 = plot(year,data,'LineWidth',3,'Color','black');
xticks([1979:1:2018]);
ax = gca;
ax.FontSize = 18;
xlabel('year','FontSize', 24, 'FontWeight', 'Bold');
ylabel('data','FontSize', 24, 'FontWeight', 'Bold');
Thank you!
0 Commenti
Risposta accettata
DGM
il 20 Nov 2021
If you just want an easy way, consider using this:
load('data.mat');
year = [1979:1:2018];
anomaly(year,data);
The colors can be set as you choose, and other plot elements overlaid as before.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Annotations in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!