首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >调整地物大小时,次轴发生移位

调整地物大小时,次轴发生移位
EN

Stack Overflow用户
提问于 2018-08-22 00:18:37
回答 2查看 155关注 0票数 3

我正在尝试用两个X轴绘制一个Matlab (R2017a)图形(填充轮廓+颜色条),在图形的底部和顶部,具有相同的比例,但不同的刻度线和标签。按照herehere的建议,我已经做到了,但是当我尝试手动调整图形窗口的大小或打印它时,设置某些不同于默认比例的比例,例如:

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轴的绘图。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 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
票数 4
EN

Stack Overflow用户

发布于 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')

上面的命令对我有效。产生以下结果:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51952894

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档