這是因爲您還沒有繪製畫布。
在繪製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