KatyB
KatyB

Reputation: 3980

plotting two yaxis with different markers and colors

If I have two y vectors and one x vector:

y1 = [0.1,0.2,0.5,0.6];
y2 = [0.3,0.4,0.7,0.8];
x = 1:length(y1);

How can I plot all of the information on the same plot using different markers and different colors. I have tried the following:

cols = {'k','r','b',[0,0.5,0]};
markers = {'s','o','d','v'};

for i = 1:4;
    plot(x(i),y1(i),markers{i},'color',cols{i},'MarkerEdgeColor',...
        cols{i},'MarkerFaceColor','w');
    hold on
end
ax1 = gca;
ax2 = axes('Position',get(ax1,'Position'),...
       'YAxisLocation','right','XColor','k','YColor','k');
linkaxes([ax1,ax2],'x'); 
for i = 1:4;
    plot(x(i),y2(i),markers{i},'color',cols{i},'MarkerEdgeColor',...
        cols{i},'MarkerFaceColor',cols{i},'Parent',ax2);
    hold on;  
end

But this seems to overwrite the first plot. My aim here it to draw the first four points (y1) with the markers and colors defined, but with the maker faces in white. I then hope to include on the same figure, a second yaxis (on the right) with the values from y2, but this time with the marker faces colored according to 'cols'. How can I do this?

Addition:

When I use plotyy

for i = 1:4;
    [ax,h1,h2] = plotyy(x(i),y1(i),x(i),y2(i));
    hold on
    set(h1,'linestyle','none','marker',markers{i},'MarkerEdgeColor',...
        cols{i},'MarkerFaceColor',cols{i});
    set(h2,'linestyle','none','marker',markers{i},'MarkerEdgeColor',...
        cols{i},'MarkerFaceColor','w');
    set(ax,{'ycolor'},{'k';'k'},{'xcolor'},{'k';'k'});
end

The xaxis values do not show up correctly, where although they are identical, they do not line up on the plot.

Upvotes: 2

Views: 3261

Answers (2)

NKN
NKN

Reputation: 6424

You can use the embedded function of Matlab , plotyy

plotyy(X1,Y1,X2,Y2) plots X1 versus Y1 with y-axis labeling on the left and plots X2 versus Y2 with y-axis labeling on the right.

check more options here.

This example graphs two mathematical functions using plot as the plotting function. The two y-axes enable you to display both sets of data on one graph even though relative values of the data are quite different.

figure
x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
[AX,H1,H2] = plotyy(x,y1,x,y2,'plot');

If you are trying with 'hold on' this solves the a-synchronized axes:

set(ax, 'XLim', [min(xaxis) max(xaxis)]);
set(ax(2),'XTick',[]);

enter image description here

Upvotes: 4

Buck Thorn
Buck Thorn

Reputation: 5073

The problem is that the background color on the overlayed plot is set to white (and opaqueness to max) so that everything underneath is invisible. Substituting the ax2 = ... statement with

ax2 = axes('Position',get(ax1,'Position'),...
'YAxisLocation','right','XColor','k','YColor','k','color','none');

should fix things.

Upvotes: 0

Related Questions