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

use*_*021 5 python matplotlib legend

我试图在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()
Run Code Online (Sandbox Code Playgroud)

矩形只是不在图中的任何位置绘制.如果我查看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.

因此我的问题是,找到传奇框架的坐标.

如果你可以帮助我,真的很棒.

感谢您阅读这篇文章.

小智 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()
Run Code Online (Sandbox Code Playgroud)