Plotting with Stem in different colours in 1 step

28 views (last 30 days)
Currently i'm using stem to plot values ina graph within a loop:
...
for i = 1:n
for i2 = 1:m
val = bla bla
colour = obj.colours(i);
stem(index, val, colour);
index = index + 1;
end
end
In order to speed things up i want to collect the values and stem them in 1 go.
I'm having issues assigning the right colour as in the loop:
...
for i = 1:n
for i2 = 1:m
vals(index) = bla bla
colours(index) = obj.colours(i);
index = index + 1;
end
end
stem(1:index-1, vals, colours);
It doesn't work.
How can i do something like this:
stem(1:index-1, vals, ['r' 'r' 'g' .... ]);
Thanks

Accepted Answer

dpb
dpb on 24 Aug 2022
Edited: dpb on 24 Aug 2022
Can't be done that way at all -- the stem plot creates a single object handle so there's only one color property for it; not multiple. You must create as many handles as points you want different colors -- this means either calling in a loop or creating a column-oriented matrix of points for the y-values to plot against the x-vector values. To use the array syntax will have to have a second row of NaN entries or it will still treat the vector a single set of points regardless of its orientation.
Unlike scatter that will take the numeric value for a color, stem will only use the RGB or hex form for color other than the few named default colors.
All these limitations and the different ways stuff works between the various similar ways to plot is really, really annoying (not to mention confusing), granted...
The only alternative I'd see would be to use scatter for the markers but then have to draw the lines separately as well which runs into the same limitations on specifying colors.

More Answers (0)

Categories

Find more on Graphics Performance in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!