繁体   English   中英

自动缩放matplotlib轴以留出图例空间

[英]Autoscale a matplotlib Axes to make room for legend

我正在使用matplotlib绘制航天器轨道的2D视图。 在此轨道上,我确定并标记了某些事件,然后在图例中列出了这些事件和相应的日期。 在将图形保存到文件之前,我会在轨道图上进行自动缩放,这会使图例直接打印在图的顶部。 我想做的是,在自动缩放后,以某种方式找出图例的宽度,然后将我的xaxis扩展到图右侧的图例的“腾出空间”。 从概念上讲,是这样的;

# ... code that generates my plot up here, then:
ax.autoscale_view()
leg = ax.get_legend()
leg_width = # Somehow get the width of legend in units that I can use to modify my axes
xlims = ax.get_xlim()
ax.set_xlim( [xlims[0], xlims[1] + leg_width] )
fig.savefig('myplot.ps',format='ps')

我遇到的主要问题是ax.set_xlim()接受“数据”特定值,而leg.get_window_extent以窗口像素为单位报告(我认为),甚至是在绘制画布之后,所以我没有确定如何以类似于上面的方式获取图例“宽度”。

您可以保存一次图形以获得真实的图例位置,然后使用transData.inverted()将屏幕坐标转换为数据坐标。

import pylab as pl
ax = pl.subplot(111)
pl.plot(pl.randn(1000), pl.randn(1000), label="ok")
leg = pl.legend()

pl.savefig("test.png") # save once to get the legend location

x,y,w,h = leg.get_window_extent().bounds

# transform from screen coordinate to screen coordinate
tmp1, tmp2 = ax.transData.inverted().transform([0, w])
print abs(tmp1-tmp2) # this is the with of legend in data coordinate

pl.savefig("test.png")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM