How can I automatically plot graphs two by two of the same color?

7 views (last 30 days)
I mean: I have ten graphs to plot on the same figure. Each graph has its own (let's call it) related-graph, which has to be plotted on the same image. I want each graph and its related-graph to be the same color!
I thought of using
hold all
whit some changes, but it doesn't work!
Here's a code example:
x = 0:1:10;
figure(1)
for a=1:10;
y = a*x;
figure(1)
plot_handle = plot(x,y);
hold on
plot(x,10*a*ones(1,length(x)),'Color',get(plot_handle,'Color'));
hold all
grid on
box on
end
1st graph (and its related) is blue: ok.
2nd graph is green: ok.
From 3rd to 10th graphs are ALL green: bad!

Answers (1)

dpb
dpb on 5 Jul 2013
One way...
M
x = 0:1:10;
color={'b';'g';'r';'c';'m';'y';'k'};
for a=1:10;
y = a*x;
c=color{fix((a+1)/2)};
plot(x,y,'color',c)
if a==1, hold on, end
plot(x,10*a,'Color',c);
end
grid on
box on
  2 Comments
Paolo Minotti
Paolo Minotti on 5 Jul 2013
Your code doesn't work properly, because, let's say, plots a=1 and a=2 have both the same color.
I know that one solution would be to create an array such as
color = ['b','g','r','c','m','y','k'];
and using the index
a
to change the color inside the loop. But this can work only if you know in advance the number of loops of the
for
loop. This is not my case, because I don't know, in advance, how many graphs I have to plot. So I would like to use
hold all
or something like that.
dpb
dpb on 5 Jul 2013
Edited: dpb on 5 Jul 2013
So, keep an independent counter...doesn't have to be a counted loop. You can also index into the 'colororder' property of the axes object instead of making up an external table; I just did it to use the mnemonic letters to be able to read the code more easily.
Or, give a more representative sample of how you're generating the pairs of plots you want to keep together to get more specific possible solutions.
The previous was simply indicating one way in which to select a given color for a specific plot--adapt to the situation or if you don't actually see how to do that, as above says, give more specific context

Sign in to comment.

Categories

Find more on 2-D and 3-D Plots in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!