如何在matplotlib的图例中绘制一个矩形?

5
我正在尝试在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。
因此,我的问题是要找到图例框架的坐标。
如果您能帮助我解决这个问题,那真是太好了。
谢谢您阅读到这里。

1
你为什么要这样做?你确定legend对象中没有内置的东西可以帮你完成吗? - tacaswell
2个回答

4
这个链接可能有你需要的内容。请点击此处查看,其中包含了关于添加到图例中的特定艺术家(也称为代理艺术家)的信息。
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()

2
问题是图例的位置事先不知道。只有在呈现图形(调用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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接