是否可以使用 matplotlib 在图例中包含一个不属于图表一部分的标题?

Is it possible to use matplotlib to include a subheading in legend that isnt a part of the graph?

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

您可以创建 2 个图例。在第二个上,您可以根据需要 create/manipulate symbol/text/title 。这是您可以尝试的可运行代码。

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()

输出图: