我已经阅读了几个关于设置两个x轴数据的答案,以及mathworks.com上的一些教程,但我看不到完全执行以下操作的方法:
正常绘制数据集1。
在图的上侧创建第二个X轴,但是使用下一个数据集的现有y轴。
绘制数据集第二个,使得它控制第二个X轴(缩放等),并且不覆盖或重新调整现有的单个Y轴。
这样做的原因是,我想基于同一个源数据集绘制两组不同的类似直方图的值,因此频率分布在数量上相似,但bin大小/边缘的值不同。
我的后退是对第二个数据集的X数据做点斜率缩放,但是我仍然需要创建一个类似于How to insert two X axis in a Matlab a plot的第二个X轴。
最佳答案
您可以在第一个轴的顶部(在同一位置)创建第二个轴,它的XAxisLocation
设置为'top'
,没有Color
,因此它是透明的,没有yticks,并且它的YLim
链接到第一个轴此外,我们可以链接Position
值,以确保如果调整其中一个轴的大小,它们将一起调整大小以保持其外观。
figure;
% Create the first axes
hax1 = axes();
% Plot something here
xdata = 1:10;
hplot1 = line(xdata, log(xdata));
% Create a transparent axes on top of the first one with it's xaxis on top
% and no ytick marks (or labels)
hax2 = axes('Position', get(hax1, 'Position'), ... % Copy position
'XAxisLocation', 'top', ... % Put the x axis on top
'YAxisLocation', 'right', ... % Doesn't really matter
'xlim', [2 20], ... % Set XLims to fit our data
'Color', 'none', ... % Make it transparent
'YTick', []); % Don't show markers on y axis
% Plot data with a different x-range here
hplot2 = line(xdata * 2, log(flip(xdata)), 'Color', 'r', 'Parent', hax2);
% Link the y limits and position together
linkprop([hax1, hax2], {'ylim', 'Position'});
% Draw some labels
xlabel(hax1, 'Blue Line')
xlabel(hax2, 'Red Line')
ylabel(hax1, 'Some Value')
% Add a legend? Why not?!
legend([hplot1, hplot2], {'Blue', 'Red'})
卡尔W编辑(专栏)
上面的代码将导致丑陋的xtick,当tick间距不是相同的顶部和底部。
我在matlab remove only top and right ticks with leaving box on找到了解决办法我把上面的代码稍微修改了一下
figure
xdata = 1:10;
plot(xdata)
% get handle to current axes
hax1 = gca;
% set box property to off
set(hax1,'box','off','color','white')
hax2 = axes('Position', get(hax1, 'Position'),'box','off', ... % Copy position
'XAxisLocation', 'top', ... % Put the x axis on top
'YAxisLocation', 'right', ... % Doesn't really matter
'Color', 'none', ... % Make it transparent
'YTick', []);
警告:这将不适用于
plot
,它将重写现有的轴赋值。因为没有
points
函数(愚蠢的数学作品),我不得不做line(x,y,'linestyle','none','marker','x','parent',hax2)
来获得分数。hplot2 = line(5:25, log((5:25)), 'Color', 'r', 'Parent', hax2);
linkprop([hax1,hax2],{'ylim','Position'});
这将导致