Clear Filters
Clear Filters

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

4 views (last 30 days)
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 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
year = [1979:1:2018]; %x axis
y0 = zeros(length(year),1); % y = 0 vector
index1 = find(data<0); %index for negative values
%% Figure %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
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');
ax = gca;
ax.FontSize = 18;
xlabel('year','FontSize', 24, 'FontWeight', 'Bold');
ylabel('data','FontSize', 24, 'FontWeight', 'Bold');
Thank you!

Accepted Answer

DGM on 20 Nov 2021
If you just want an easy way, consider using this:
year = [1979:1:2018];
The colors can be set as you choose, and other plot elements overlaid as before.

More Answers (0)




Community Treasure Hunt

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

Start Hunting!