【问题标题】:Title for matplotlib legendmatplotlib 图例的标题
【发布时间】:2023-04-01 11:44:01
【问题描述】:

我知道为图例设置标题似乎是多余的,但是否可以使用 matplotlib?

这是我拥有的代码的 sn-p:

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

one = mpatches.Patch(facecolor='#f3f300', label='label1', linewidth = 0.5, edgecolor = 'black')
two = mpatches.Patch(facecolor='#ff9700', label = 'label2', linewidth = 0.5, edgecolor = 'black')
three = mpatches.Patch(facecolor='#ff0000', label = 'label3', linewidth = 0.5, edgecolor = 'black')

legend = plt.legend(handles=[one, two, three], loc = 4, fontsize = 'small', fancybox = True)

frame = legend.get_frame() #sets up for color, edge, and transparency
frame.set_facecolor('#b4aeae') #color of legend
frame.set_edgecolor('black') #edge color of legend
frame.set_alpha(1) #deals with transparency
plt.show()

我想要 label1 上方的图例标题。作为参考,这是输出:

【问题讨论】:

标签: python matplotlib patch


【解决方案1】:

在这一行添加title参数:

legend = plt.legend(handles=[one, two, three], title="title",
                    loc=4, fontsize='small', fancybox=True)

另请参阅official docs for the legend constructor

【讨论】:

  • 你也可以通过title_fontsize参数控制标题的大小
【解决方案2】:

只是为了补充接受的答案,这也适用于 Axes 对象。

fig, ax = plt.subplots()
ax.plot([0, 1, 2], [0, 1, 4], label='some_label') # Or however the Axes was created.
ax.legend(title='This is My Legend Title')

【讨论】:

    【解决方案3】:

    如果您已经创建了图例,可以使用set_title() 修改其标题。对于第一个答案:

    legend = plt.legend(handles=[one, two, three], loc=4, fontsize='small', fancybox=True)
    legend.set_title("title")   
    # plt.gca().get_legend().set_title() if you didn't store the
    # legend in an object or you're loading a saved figure. 
    

    对于基于 Axes 的第二个答案:

    fig, ax = plt.subplots()
    ax.plot([0, 1, 2], [0, 1, 4], label='some_label') # Or however the Axes was created.
    ax.legend()
    ax.get_legend().set_title("title")
    

    【讨论】:

      猜你喜欢
      • 2019-05-28
      • 1970-01-01
      • 2021-11-01
      • 1970-01-01
      • 2011-11-23
      • 1970-01-01
      • 2014-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多