带有2个y轴和datetick的散点图 [英] Scatter with 2 y-axes and datetick
问题描述
我非常感谢您的帮助.
我要独立的数据集.每个数据集包含两个变量:日期(作为日期编号)和相应的数据.我需要在一个散点图中绘制两个数据集,在x轴上绘制日期,在两个y轴上绘制日期.我一直在尝试以下代码:
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');
现在,这在右侧给出了正确的y轴,但是在右侧,我最终得到了两个重叠的y轴. 另外,我需要更改x轴,以便它显示日期而不是日期数字.我试图将datetick合并到代码中,但这又给了我两个重叠的x轴.
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.
有人知道怎么做吗?
谢谢
推荐答案
我使用示例输入尝试了您的脚本,但没有发现问题.无论如何,这是一个使用matlab函数plotyy
的解决方案,该函数适用于像这样的简单绘图:
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');
在没有datetick
调用的情况下,plotyy
函数将图形中的xtick
同步.调用datetick
时,它将重新计算滴答声,除非您明确指示不这样做,请参见选项keepticks
,这被视为两组x
轴(即使x
坐标相同) ,刻度线位于不同的位置).需要keeplimits
选项来保留原始的xlim
.显然,需要更多的人工工作才能获得足够漂亮的图.
Without the datetick
call the plotyy
function synchronizes the xtick
s 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.
更新:最初缺少keeplimits
Update2 :已更改示例数据以与更新的问题评论相对应
Update2: changed sample data to correspond to updated question comment
这篇关于带有2个y轴和datetick的散点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!