I want to change the backgroung color of my plots.

3 views (last 30 days)
I want to draw a graph in which for any rang that graph shows different backgroung it shows. for example in the range of o-1 red background, in 1-2 blu, in 2-3 yellow and so forth.
could I do that in matlab?

Accepted Answer

Voss
Voss on 7 May 2022
Is something like this what you mean?
colors = [1 0 0; 0 0 1; 1 1 0];
thresholds = [1 2];
figure()
subplot(2,1,1)
x = 0:0.05:2*pi;
y = 1.5+1.5*sin(x);
plot(x,y,'k','LineWidth',2);
xlim([0 2*pi]);
ylim([0 3]);
set_background(x,y,colors,thresholds)
subplot(2,1,2)
x = 0:0.025:2*pi;
y = 1.5+1.5*sin(x)+0.45*randn(1,numel(x));
plot(x,y,'k','LineWidth',2);
xlim([0 2*pi]);
ylim([-2 5]);
set_background(x,y,colors,thresholds)
function set_background(x,y,colors,thresholds)
idx = ones(1,numel(x));
thresholds = [-Inf thresholds Inf];
for ii = 2:numel(thresholds)
idx(y >= thresholds(ii-1) & y < thresholds(ii)) = ii-1;
end
yl = get(gca(),'YLim').';
x = (x(1:end-1)+x(2:end))/2;
x = [2*x(1)-x(2) x 2*x(end)-x(end-1)];
p = patch( ...
'XData',x((2:end)+[0;0;-1;-1;0]), ...
'YData',repmat(yl([1 2 2 1 1]),1,numel(x)-1), ...
'FaceColor','flat', ...
'FaceVertexCData',colors(idx,:), ...
'EdgeColor','none');
ch = get(gca(),'Children');
ch(ch == p) = [];
set(gca(),'Children',[ch(:); p],'Layer','top');
end
  6 Comments

Sign in to comment.

More Answers (0)

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!