Scatter with 2 y-axes and datetick

2019-08-30 04:22发布

问题:

I would really appreciate some help.

I have to independent datasets. Each dataset contains two variables: dates (as datenumber) and corresponding data. I need to plot both datasets on one scatter plot with dates on x-axis and two y-axes. I have been trying with the following code:

figure(1); 
scatter(x1,y1,'g'); 
set(gca); 
ax1=gca;
set(ax1,'YColor','g'); 
ax2 = axes('Position',get(gca,'Position'),'YAxisLocation','right', XTick'[],'Color','none','YColor','r'); 
hold on; scatter(x2,y2,'r');

Now, this gives correct y-axis on the right side, however on the right side I end up with two overlapping y-axes. Also, I need to change x-axis so that it displays dates as opposed to datenumbers. I've tried to incorporate datetick into the code but it again gives me two overlapping x-axes.

Does anyone know how to go about it?

thank you

回答1:

I tried your script with your sample input and found no problems. Anyway, here's a solution which uses the matlab function plotyy, which is suited to simple plots like this:

%generate input
x1=[732490 732509 732512 732513 732521 732528];
y1=[7.828 7.609 22.422 14.758 26.258 1.477];
x2=[732402 732403 732404 732404 732433];
y2=[0.693 0.645 0.668 0.669 0.668];

figure(1); 
[ax, h1,h2]=plotyy(x1,y1,x2,y2,'scatter');

%set colors manually
green=[0 1 0];
red=[1 0 0];
set(h1,'cdata',green);
set(h2,'cdata',red);
set(ax(1),'ycolor',green);
set(ax(2),'ycolor',red);

%note the 'keepticks' and 'keeplimits' options
datetick(ax(1),'x','yyyy-mm-dd','keepticks','keeplimits');
datetick(ax(2),'x','yyyy-mm-dd','keepticks','keeplimits');

Without the datetick call the plotyy function synchronizes the xticks in the plot. When you call datetick, it recalculates the ticks, unless you explicitly tell it not to, see the option keepticks, and this is seen as two sets of x axes (even though the x coordinates are the same, the ticks are located at different positions). The keeplimits option is needed to preserve the original xlim. It obviously needs some more manual work to get plots like this sufficiently pretty.

Also note that I set the axes and data colors manually: there might be a way to do this more elegantly.

Update: keeplimits originally missing

Update2: changed sample data to correspond to updated question comment