【问题标题】:Is it possible to use matplotlib to include a subheading in legend that isnt a part of the graph?是否可以使用 matplotlib 在图例中包含一个不属于图表的子标题?
【发布时间】:2020-07-22 08:08:05
【问题描述】:

我正在使用 matplotlib 绘制饼图。我在图表中添加了一个图例。但是,我想在图例中添加一个“总计”,以总结所有其他类别的值。因此,“总计”的值不会成为饼图的一部分,只会显示在图例中。我可以这样做吗?谢谢。

【问题讨论】:

标签: python-3.x matplotlib plot graph pie-chart


【解决方案1】:

您可以创建 2 个图例。在第二个中,您可以根据需要创建/操作符号/文本/标题。这是一个可运行的代码,您可以尝试一下。

from matplotlib import pyplot as plt
import matplotlib.patches as mpatches
import numpy as np

fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.axis('equal')
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
ax.pie(students, labels = langs,autopct='%1.2f%%')

# first legend
lgn = plt.legend()
ax = plt.gca().add_artist(lgn)

# second legend
gold_patch = mpatches.Patch(color='gold', label='Total= 9999')  # use your description text here
second_legend = plt.legend(handles=[gold_patch], loc=1, \
                           bbox_to_anchor=(0.5, 0.35, 0.55, 0.35)) # adjust location of legend here
second_legend.set_frame_on(False)  # use True/False as needed
second_legend.set_title("Other categories")

plt.show()

输出图:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-19
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    相关资源
    最近更新 更多