2011-02-16 107 views
4

我需要知道圖例大小的像素。我似乎只能夠從任何功能得到高度= 1,...我已經試過以下Matplotlib圖例像素高度

這個返回1

height = legend.get_frame().get_bbox_to_anchor().height 

這將返回[0,0],[1。 ,1]

box = legend.get_window_extent().get_points() 

這也將返回[0,0],[1,1]

box = legend.get_frame().get_bbox().get_points() 

所有這些返回1,即使傳說中的大小而變化!這是怎麼回事?

+0

你是如何創造你的傳奇?這返回什麼:`type(leg.get_frame())`?你使用的是什麼版本的matplotlib? – Paul 2011-02-16 13:59:11

回答

3

這是因爲您還沒有繪製畫布。

在繪製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)保存,而不是在屏幕上繪製,因此像素大小將會不同。

這種情況有解決方法有兩種:

  1. 快速和骯髒的:輸出像素值之前畫出人物的帆布,並確保在保存時要明確指定人物的DPI(如fig.savefig('temp.png', dpi=fig.dpi)

  2. 建議但稍微複雜一點:將回調連接到繪圖事件,並且只在繪製圖形時使用像素值,這允許您在僅繪製一次圖形的同時使用像素值。

作爲後一種方法的一個簡單的例子:

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)。

無論如何,希望這是有道理的。

+0

你知道爲什麼1 * dpi不會導致渲染後的像素高度。即爲什麼繪畫之前它總是1? – Duncan 2011-02-17 08:52:06