gpt4 book ai didi

python - 在所有子图的顶部显示图例

转载 作者:太空宇宙 更新时间:2023-11-04 10:20:28 24 4
gpt4 key购买 nike

我有 1x3 的 matplotlib 子图。我试图在所有子图的顶部显示子图的图例。但是,我只显示最后一个。

df = pd.DataFrame({"a":[1,2,3],"b":[4,5,6],"c":[7,8,9]})
fig, axes = plt.subplots(nrows=1, ncols=3)
df.plot(ax=axes[0],legend=False)
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
ncol=2, mode="expand", borderaxespad=0.)
df.plot(ax=axes[1],legend=False)
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
ncol=2, mode="expand", borderaxespad=0.)
df.plot(ax=axes[2],legend=False)
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
ncol=2, mode="expand", borderaxespad=0.)

enter image description here

如何在所有子图的顶部显示图例?

最佳答案

使用 ax.legend(...) 而不是 plt.legend

一般来说,最好避免混合使用 pyplot 和 axes 方法。事实上,我建议或多或少只使用 plt.subplots()plt.show() 并在其他地方使用轴/图形方法。它使在哪些轴上绘制以及对图形与轴的操作变得更加清晰。

举个例子:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({"a":[1,2,3],"b":[4,5,6],"c":[7,8,9]})

fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(10, 4))
for ax in axes:
df.plot(ax=ax,legend=False)
ax.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
ncol=2, mode="expand", borderaxespad=0.)

# Make some room at the top for the legend...
fig.subplots_adjust(top=0.8)

plt.show()

enter image description here

关于python - 在所有子图的顶部显示图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32569632/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com