2012-10-03 72 views
5

我想繪製一個矩形到matplotlib中的圖例。如何在matplotlib中的圖例上繪製一個矩形?

爲了說明如何到目前爲止,我已經得到了我展示我最好的嘗試,這是不行的:

import matplotlib.pyplot as plt 
from matplotlib.patches import Rectangle 
import numpy as np 

Fig = plt.figure() 
ax = plt.subplot(111) 

t = np.arange(0.01, 10.0, 0.01) 
s1 = np.exp(t) 
ax.plot(t, s1, 'b-', label = 'dots') 

leg = ax.legend() 

rectangle = Rectangle((leg.get_frame().get_x(), 
        leg.get_frame().get_y()), 
        leg.get_frame().get_width(), 
        leg.get_frame().get_height(), 
        fc = 'red' 
       ) 

ax.add_patch(rectangle) 

plt.show() 

矩形恰恰是沒有任何地方在圖繪製。 (),get_x(),leg.get_frame()。get_y()),leg.get_frame()。get_width()和leg.get_frame()。get_height(),I看到它們分別是0.0,0.0,1.0和1.0,。

因此,我的問題是要找到圖例框架的座標。

如果你能幫助我,這將是非常好的。

感謝您閱讀這篇文章。

+1

你爲什麼要這麼做?你確定沒有內置到'legend'對象中的東西可以幫你嗎? – tacaswell

回答

2

問題在於圖例的位置並未提前知道。只有當您呈現圖形(稱爲plot())時,才決定該位置。

我來的解決方案across就是畫兩次圖。另外,我使用了座標軸(默認是數據座標)並縮放矩形,所以您仍然可以看到它背後的一些圖例。請注意,我必須設置圖例和矩形zorder以及;圖例會比矩形更晚繪製,因此矩形會在圖例後面消失。

import numpy as np 
import matplotlib.pyplot as plt 
from matplotlib.patches import Rectangle 

Fig = plt.figure() 
ax = plt.subplot(111) 

t = np.arange(0.01, 10.0, 0.01) 
s1 = np.exp(t) 
ax.plot(t, s1, 'b-', label = 'dots') 

leg = ax.legend() 
leg.set_zorder(1) 
plt.draw() # legend position is now known 
bbox = leg.legendPatch.get_bbox().inverse_transformed(ax.transAxes) 
rectangle = Rectangle((bbox.x0, bbox.y0), 
         bbox.width*0.8, bbox.height*0.8, 
         fc='red', transform=ax.transAxes, zorder=2) 
ax.add_patch(rectangle) 
plt.show()