
How to plot a different colored area of negative and positive elements in an array?
14 views (last 30 days)
Show older comments
Hey guys: Can you please help me to get my goal? my goal will be listed below. 1) Plot a 2D area of the all elements in an array. x-axis and y-axis are the order of array and the value of each element. 2)The area has two colors because the values can be positive or negative.In other words, the color is separated by x-axis 3)The different colored area is connected. The area in my pic is unconnected.
This is my code(I mean the code is wrote by myself but the hints from someone else in community, thanks dude) :
clear all,clc
% random data,my real data has more than 10k elements
Data=[3,4,-4,5,1,-4,-2,1,5,5];
% length of the array
Length=[1:10];
% threshold is zero
base=Data>0;
% 2 arrays have the same data as Data
above=Data;
below=Data;
% change the ceratin data to be nan
above(~base)=nan;
below(base)=nan;
% plot
% % The area is unconnected, that is main part of my question
area(Length,above,'FaceColor','r');
hold on
area(Length,below,'FaceColor','b');

0 Comments
Answers (2)
Scott MacKenzie
on 7 May 2021
Fang: Did you find a good solution? I've been working on this issue recently. Here's an approach that works well. The trick is to first expand your data through interpolation and then use the area function. Do this and the transitions are smooth.
% your example data
Data =[3 4 -4 5 1 -4 -2 1 5 5];
x = 1:length(Data);
% interpolate to get smoother +/- transitions
n = 1000;
x9 = linspace(1,length(x),n);
y9 = interp1(x,Data,x9);
above = y9;
below = y9;
above = above .* (above >= 0);
below = below .* (below <= 0);
area(x9, above, 'FaceColor', 'r');
hold on;
area(x9, below, 'FaceColor', 'b');

KL
on 1 Nov 2017
pos = Data;
pos(pos<0)=nan;
neg = Data;
neg(neg<0)=nan;
area(pos)
hold on
area(neg)
See Also
Categories
Find more on Surface and Mesh Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!