【问题标题】:How do I draw a rectangle on the legend in matplotlib?如何在 matplotlib 的图例上绘制一个矩形?
【发布时间】:2012-10-03 04:46:44
【问题描述】:

我正在尝试在 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。

因此,我的问题是找到图例框架的坐标。

如果你能帮助我,那就太好了。

感谢您阅读本文。

【问题讨论】:

  • 你为什么要这样做?你确定legend 对象中没有内置的东西可以为你做这件事吗?

标签: python matplotlib legend


【解决方案1】:

此链接可能包含您正在寻找的确切内容。 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()

【讨论】:

    【解决方案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()
    

    【讨论】:

      猜你喜欢
      • 2016-09-22
      • 2022-08-06
      • 2016-11-24
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多