Python 在所有子地块的顶部显示图例

Python 在所有子地块的顶部显示图例,python,matplotlib,Python,Matplotlib,我有一个带有matplotlib的1x3子图。 我试图在所有子地块的顶部显示子地块的传奇。但是,我只展示了最后一个 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,

我有一个带有matplotlib的1x3子图。 我试图在所有子地块的顶部显示子地块的传奇。但是,我只展示了最后一个

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

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

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

通常,最好避免混合pyplot和Axis方法。事实上,我建议或多或少只使用
plt.subplot()
plt.show()
,并在其他地方使用axes/figure方法。它可以更清楚地显示正在绘制的轴,以及图形与轴之间的操作

例如:

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

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

通常,最好避免混合pyplot和Axis方法。事实上,我建议或多或少只使用
plt.subplot()
plt.show()
,并在其他地方使用axes/figure方法。它可以更清楚地显示正在绘制的轴,以及图形与轴之间的操作

例如:

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

您是否尝试过将
plt.legend
替换为
axes[i]。legend()
?是否尝试过将
plt.legend
替换为
axes[i]。legend()