繁体   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