How to fill the area between two curves with discrete data and with a condition (y<0 & y>0)?

조회 수: 4 (최근 30일)
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!

채택된 답변

DGM
DGM 2021년 11월 20일
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.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Annotations에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by