簡體   English   中英

如何在matplotlib中的圖例上繪制一個矩形?

[英]How do I draw a rectangle on the legend in 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()

矩形只是不在圖中的任何位置繪制。 如果我查看leg.get_frame()。get_x(),leg.get_frame()。get_y()),leg.get_frame()。get_width()和leg.get_frame()。get_height()的值,我看到了他們分別是0.0,0.0,1.0和1.0。

因此我的問題是找到傳說框架的坐標。

如果你可以幫助我,真的很棒。

感謝您閱讀這篇文章。

麻煩的是,傳說的位置不是事先知道的。 只有在你渲染圖形時(調用plot() ),才會確定位置。

我來了一個解決方案跨越是繪制數字的兩倍。 另外,我使用了軸坐標(默認是數據坐標)並縮放了矩形,所以你仍然可以看到它背后的傳說。 請注意,我還必須設置圖例和矩形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()

此鏈接可能具有您正在尋找的確切內容。 http://matplotlib.org/users/legend_guide.html#creating-artists-specifically-for-adding-to-the-legend-aka-proxy-artists

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

red_patch = mpatches.Patch(color='red', label='The red data')
plt.legend(handles=[red_patch])

plt.show()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM