non-homogenous grouped data in MATLAB plotyy()

匆匆过客 提交于 2019-12-24 17:24:58

问题


I have to plot 1 line plot and 3 grouped scatter plots in a single plot window.

The following is the code I tried,

figure;
t1=0:0.1:10;
X = 2*sin(t1);
ts = 0:1:10;
Y1 = randi([0 1],length(ts),1);
Y2 = randi([0 1],length(ts),1);
Y3 = randi([0 1],length(ts),1);
plotyy(t1,X,[ts',ts',ts'],[Y1,Y2,Y3],'plot','scatter');
%plotyy(t1,X,[ts',ts',ts'],[Y1,Y2,Y3],'plot','plot');

The following are my questions,

  1. The above code works if I replace 'scatter' by 'plot' (see commented out line), but 'scatter' works only for 1 data set and not for 3. Why?

  2. How to individually assign colors to the 3 grouped scatter plots or plots?


回答1:


Read the error message you're given:

Error using scatter (line 44) X and Y must be vectors of the same length.

If you look at the documentation for scatter you'll see that the inputs must be vectors and you're attempting to pass arrays.

One option is to stack the vectors:

plotyy(t1,X,[ts';ts';ts'],[Y1;Y2;Y3],'plot','scatter');

But I don't know if this is what you're looking for, it certainly doesn't look like the commented line. You'll have to clarify what you want the final plot to look like.

As for the second question, I would honestly recommend not using plotyy. I may be biased but I've found it far to finicky for my tastes. The method I like to use is to stack multiple axes and plot to each one. This gives me full control over all of my graphics objects and plots.

For example:

t1=0:0.1:10;
X = 2*sin(t1);
ts = 0:1:10;
Y1 = randi([0 1],length(ts),1);
Y2 = randi([0 1],length(ts),1);
Y3 = randi([0 1],length(ts),1);

% Create axes & store handles
h.myfig = figure;
h.ax1 = axes('Parent', h.myfig, 'Box', 'off');
h.ax2 = axes('Parent', h.myfig, 'Position', h.ax1.Position, 'Color', 'none', 'YAxisLocation', 'Right');

% Preserve axes formatting
hold(h.ax1, 'on');
hold(h.ax2, 'on');

% Plot data
h.plot(1) = plot(h.ax1, t1, X);
h.scatter(1) = scatter(h.ax2, ts', Y1);
h.scatter(2) = scatter(h.ax2, ts', Y2);
h.scatter(3) = scatter(h.ax2, ts', Y3);

Gives you:

And now you have full control over all of the axes and line properties. Note that this assumes you have R2014b or newer in order to use the dot notation for accessing the Position property of h.ax1. If you are running an older version you can use get(h.ax1, 'Position') instead.



来源:https://stackoverflow.com/questions/30655347/non-homogenous-grouped-data-in-matlab-plotyy

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