这是因为您还没有绘制画布。
在绘制canvas之前,matplotlib中不存在像素值(或者说,它们存在,与屏幕或其他输出无关)。
这有很多原因,但我现在就跳过它们。只要说matplotlib尽量保持一般,并且通常避免使用像素值直到绘制东西。
举个简单的例子:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10), label='Test')
legend = ax.legend(loc='upper left')
print 'Height of legend before canvas is drawn:'
print legend.get_window_extent().height
fig.canvas.draw()
print 'Height of legend after canvas is drawn:'
print legend.get_window_extent().height
然而,这仅仅是要代表传奇的高度以像素为单位,因为它在屏幕上绘制!如果保存该图形,它将以不同的dpi(默认值为100)保存,而不是在屏幕上绘制,因此像素大小将会不同。
这种情况有解决方法有两种:
快速和肮脏的:输出像素值之前画出人物的帆布,并确保在保存时要明确指定人物的DPI(如fig.savefig('temp.png', dpi=fig.dpi)
建议但稍微复杂一点:将回调连接到绘图事件,并且只在绘制图形时使用像素值,这允许您在仅绘制一次图形的同时使用像素值。
作为后一种方法的一个简单的例子:
import matplotlib.pyplot as plt
def on_draw(event):
fig = event.canvas.figure
ax = fig.axes[0] # I'm assuming only one subplot here!!
legend = ax.legend_
print legend.get_window_extent().height
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10), label='Test')
legend = ax.legend(loc='upper left')
fig.canvas.mpl_connect('draw_event', on_draw)
fig.savefig('temp.png')
通知在什么打印为图例用于第一和第二实施例中的高度不同。 (第二次是31.0,第一次是24.8,在我的系统上是第一次,但这取决于your .matplotlibrc file的默认设置)
不同之处在于默认的fig.dpi
(默认为80 dpi)和保存数字时的默认分辨率(默认为100 dpi)。
无论如何,希望这是有道理的。
你是如何创造你的传奇?这返回什么:`type(leg.get_frame())`?你使用的是什么版本的matplotlib? – Paul 2011-02-16 13:59:11