2012-05-10 62 views
1

我正在使用matplotlib绘制航天器轨道的2D视图。在此轨道上,我确定并标记某些事件,然后在图例中列出这些事件和相应的日期。在将图保存到文件之前,我会在自己的轨道图上自动缩放,这会导致图例直接打印在我的图上。我想要做的是,在自动缩放之后,以某种方式查明我的传奇的宽度,然后展开我的x轴,为剧情右侧的传说“腾出空间”。从概念上讲,就像这样;自动缩放matplotlib为传奇腾出空间的轴

# ... 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报告(我认为),甚至是画布已经绘就只有后,所以我不知道我如何才能以类似于上面的方式获得图例的“宽度”。

回答

0

您可以保存图形一次以获取真实的图例位置,然后使用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")