我正在尝试用两个X轴绘制一个Matlab (R2017a)图形(填充轮廓+颜色条),在图形的底部和顶部,具有相同的比例,但不同的刻度线和标签。按照here和here的建议,我已经做到了,但是当我尝试手动调整图形窗口的大小或打印它时,设置某些不同于默认比例的比例,例如:
set(gcf,'PaperUnits','centimeters','PaperPosition',[0 0 30 15])
print(gcf,'-dpng',path,'-r300')
新的轴会发生位移:
我用Matlab中的peaks示例数据重现了我的问题:
contourf(peaks)
ax1=gca;
colorbar
set(ax1,'box','off','color','none') % get rid of the box in order not to have duplicated tick marks
ax1_pos = ax1.Position; % position of first axes
ax2 = axes('Position',ax1_pos,... % set the new pair of axes
'XAxisLocation','top',...
'YAxisLocation','Right',...
'Color','none');
set(ax2, 'XLim', get(ax1, 'XLim'), 'YLim', get(ax1, 'YLim')); % set same limits as for ax1
set(ax2, 'XTick', 0:14:42, 'XTickLabels', {'a','a','a','a'},... % set new tick marks and labels for the top X axis.
'YTick', get(ax1, 'YTick'), 'YTickLabels', []);
奇怪的是,如果我删除colobar命令,只绘制填充的轮廓,图形就会正确地运行:
有没有人知道为什么会发生这种情况(以及如何解决)?我也愿意通过其他方式实现两个X轴的绘图。
发布于 2018-08-22 18:42:56
你的问题是一个轴有一个颜色条,而另一个轴没有,即使你想给两个轴都添加一个颜色条,也会有很多自动的事情发生,会以不同的方式调整你的轴的大小。
但是,我们可以添加一个事件侦听器并定义一个函数来操作,使两个轴相同。侦听器将确保它捕获事件(调整大小)并调用我们定义的函数。这是我为此编写的代码:
%% this creates the listener for change of size in the figure
f = figure('SizeChangedFcn',@(src,evn) fixaxis(src));
%% this is your code
contourf(peaks)
ax1=gca;
colorbar
set(ax1,'box','off','color','none') % get rid of the box in order not to have duplicated tick marks
ax1_pos = ax1.Position; % position of first axes
ax2 = axes('Position',ax1_pos,... % set the new pair of axes
'XAxisLocation','top',...
'YAxisLocation','Right',...
'Color','none');
set(ax2, 'XLim', get(ax1, 'XLim'), 'YLim', get(ax1, 'YLim')); % set same limits as for ax1
set(ax2, 'XTick', 0:14:42, 'XTickLabels', {'a','a','a','a'},... % set new tick marks and labels for the top X axis.
'YTick', get(ax1, 'YTick'), 'YTickLabels', []);
%% this will resize the axis if 2 of them exist
function fixaxis(src)
ax=findall(src,'Type','Axes');
if length(ax)==2
ax(2).Position=ax(1).Position;
end
end
发布于 2018-08-22 03:42:18
同时尝试将'PaperPositionMode'
设置为'auto'
set(gcf,'PaperUnits','centimeters','PaperPosition', [0 0 30 15], 'PaperPositionMode', 'auto');
% then print
print(gcf, '-dpng', 'myFile', '-r300')
上面的命令对我有效。产生以下结果:
https://stackoverflow.com/questions/51952894
复制相似问题