Car*_*oft 3 matlab plot matlab-figure
我已经阅读了几个关于为数据设置两个x轴的SO答案,以及在mathworks.com上的一些教程,但我没有看到完全如下的方法:
通常绘制数据集第一.在图形的顶部创建第二个x轴,但使用现有的y轴作为下一个数据集.绘制第二个数据集,使其控制第二个x轴(缩放等),并且不会覆盖或重新缩放现有的单个y轴.
这样做的原因是我想基于相同的源数据集绘制两组不同的直方图值,因此频率分布的大小相似,但是bin大小/边的值是不同的.
我的后备是对第二个数据集的x数据进行点斜率缩放,但是我仍然需要创建第二个x轴,类似于如何在Matlab中插入两个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'})
Run Code Online (Sandbox Code Playgroud)
当刻度间距不同于顶部和底部时,上面的代码将导致丑陋的XTicks.我在matlab找到了一个解决方法,只删除顶部和右侧的刻度线.我稍微修改了上面的代码
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', []);
Run Code Online (Sandbox Code Playgroud)
plot
,这将覆盖现有的轴分配.由于没有points
功能(愚蠢的MathWorks),我不得不做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'});
Run Code Online (Sandbox Code Playgroud)