Plot multiple similar data in same graph

后端 未结 2 824
感动是毒
感动是毒 2021-01-16 14:03

I wanted to generate a plot (X vs Y), and Z values depend on the Y. The example is shown in the figure below. The matrix size of X is same with Z but not Y. I can plot Z aga

2条回答
  •  难免孤独
    2021-01-16 14:43

    I'll clarify the ideas I wrote in a comment. First, let's get some data:

    x = 470:0.1:484;
    z1 = cos(x)/2;
    z2 = sin(x)/3;
    z3 = cos(x+0.2)/2.3;
    

    I'll plot just three data sets, all of this is trivial to extend to any number of data sets.

    Idea 1: multiple axes

    The idea here is simply to use subplot to create a small-multiple type plot:

    ytick = [-0.5,0.0,0.5];
    ylim = [-0.9,0.9]);
    figure
    
    h1 = subplot(3,1,1);
    plot(x,z1);
    set(h1,'ylim',ylim,'ytick',ytick);
    title('z1')
    
    h2 = subplot(3,1,2);
    plot(x,z2);
    set(h2,'ylim',ylim,'ytick',ytick);
    title('z2')
    
    h3 = subplot(3,1,3);
    plot(x,z3);
    set(h3,'ylim',ylim,'ytick',ytick);
    title('z3')
    

    Note that it is possible to, e.g., remove the tick labels from the top two plot, leaving only labels on the bottom one. You can then also move the axes so that they are closer together (which might be necessary if there are lots of these lines in the same plot):

    set(h1,'xticklabel',[],'box','off')
    set(h2,'xticklabel',[],'box','off')
    set(h3,'box','off')
    set(h1,'position',[0.13,0.71,0.8,0.24])
    set(h2,'position',[0.13,0.41,0.8,0.24])
    set(h3,'position',[0.13,0.11,0.8,0.24])
    axes(h1)
    title('')
    ylabel('z1')
    axes(h2)
    title('')
    ylabel('z2')
    axes(h3)
    title('')
    ylabel('z3')
    

    Idea 2: same axes, plot with offset

    This is the simpler approach, as you're dealing only with a single axis. @Zizy Archer already showed how easy it is to shift data if they're all in a single 2D matrix Z. Here I'll just plot z1, z2+2, and z3+4. Adjust the offsets to your liking. Next, I set the 'ytick' property to create the illusion of separate graphs, and set the 'yticklabel' property so that the numbers along the y-axis match the actual data plotted. The end result is similar to the multiple axes plots above, but they're all in a single axes:

    figure
    plot(x,z1);
    hold on
    plot(x,z2+2);
    plot(x,z3+4);
    ytick = [-0.5,0.0,0.5];
    set(gca,'ytick',[ytick,ytick+2,ytick+4]);
    set(gca,'yticklabel',[ytick,ytick,ytick]);
    text(484.5,0,'z1')
    text(484.5,2,'z2')
    text(484.5,4,'z3')
    

提交回复
热议问题