How do I pass an array of line specifications or styles to plot?

时光怂恿深爱的人放手 提交于 2020-01-07 02:49:06

问题


I want to plot multiple lines with one call to plot(), with different line styles for each line. Here's an example:

Both

plot([1,2,3]', [4,5;6,7;8,9], {'-o', '-x'})

and

hs = plot([1,2,3]', [4,5;6,7;8,9])
set(hs, 'LineStyle', {'--'; '-'})

don't work. I've tried a whole bunch of arcane combinations with square and curly braces, but nothing seems to do the trick.

I know it's possible to loop through the columns in Y and call plot() for each one (like in this question), but that isn't what I'm after. I would really like to avoid using a loop here if possible.

Thanks.

PS: I found this 'prettyPlot' script which says it can do something like this, but I want to know if there's any built-in way of doing this.

PPS: For anyone who wants a quick solution to this, try this:

for i = 1:length(hs)
   set(hs(i), 'Marker', markers{i}); 
   set(hs(i), 'LineStyle', linestyles{i}); 
end

e.g. with markers = {'+','o','*','.','x','s','d','^','v','>','<','p','h'}


回答1:


Referring to http://www.mathworks.com/help/matlab/ref/plot.html, this is how to draw multiple lines with a single plot command:

plot(X1,Y1,LineSpec1,...,Xn,Yn,LineSpecn)

So your idea of

plot([1,2,3]', [4,5;6,7;8,9], {'-o', '-x'})

must be written as:

plot([1,2,3]', [4,6,8], '-o', [1,2,3]',[5,7,9],'-x')

resulting:

Reorganize input parameters into cell arrays and use cellfun to apply plot command to each cell element.

x = [1,2,3]';
xdata = {x;x};
ydata = {[4,6,8];[5,7,9]};    
lspec = {'-o';'-x'};

hold all;
cellfun(@plot,xdata,ydata,lspec);


来源:https://stackoverflow.com/questions/40058490/how-do-i-pass-an-array-of-line-specifications-or-styles-to-plot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!