如何使用 matplotlib 为许多子图制作单个图例? [英] how do I make a single legend for many subplots with matplotlib?
问题描述
我正在绘制相同类型的信息,但针对不同的国家,使用 matplotlib 绘制多个子图.也就是说,我在 3x3 网格上有 9 个图,所有线都相同(当然,每行不同的值).
I am plotting the same type of information, but for different countries, with multiple subplots with matplotlib. That is, I have 9 plots on a 3x3 grid, all with the same for lines (of course, different values per line).
但是,我还没有想出如何在图形上放置一个图例(因为所有 9 个子图都有相同的线条)一次.
However, I have not figured out how to put a single legend (since all 9 subplots have the same lines) on the figure just once.
我该怎么做?
推荐答案
还有一个很好的函数 get_legend_handles_labels()
你可以在最后一个轴上调用(如果你迭代它们),它将收集label=
参数中你需要的一切:
There is also a nice function get_legend_handles_labels()
you can call on the last axis (if you iterate over them) that would collect everything you need from label=
arguments:
handles, labels = ax.get_legend_handles_labels()
fig.legend(handles, labels, loc='upper center')
这篇关于如何使用 matplotlib 为许多子图制作单个图例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!