Matplotlib图例未显示在子图上

2024-10-01 11:31:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我不能让图例显示在子图上,它们显示得很好,并采用我应用的其他格式。我错过了什么?在

如果我单独为数据帧绘制,它会显示图例。如果我为子批次的绘图添加标签,它会将该标签分配给所有三条线。在

这是图像。绘图与子绘图

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from functools import reduce

%matplotlib notebook

#Source for files
# Per Capita Personal Income
# Ann Arbor https://fred.stlouisfed.org/series/ANNA426PCPI
# MI https://fred.stlouisfed.org/series/MIPCPI
# USA https://fred.stlouisfed.org/series/A792RC0A052NBEA

dfAnnArbor_PCPI = pd.read_csv('PerCapitaPersonalIncomeAnnArborMI.csv', skiprows=1, names=['Date', 'PCPI'])
dfMI_PCPI = pd.read_csv('PerCapitaPersonalIncomeMI.csv', skiprows=1, names=['Date', 'PCPI'])
dfUSA_PCPI = pd.read_csv('PerCapitaPersonalIncomeUSA.csv', skiprows=1, names=['Date', 'PCPI'])

# consolidate three df into one using Date
dfAll = [dfAnnArbor_PCPI, dfMI_PCPI, dfUSA_PCPI]
dfPCPI = reduce(lambda left, right: pd.merge(left, right, on='Date', how='outer'), dfAll)

dfPCPI = dfPCPI.dropna() # drop rows with NaN
dfPCPI.columns = ['Date', 'AnnArbor', 'MI', 'USA'] # rename columns
dfPCPI['Date'] = dfPCPI['Date'].str[:4] # select only year
dfPCPI = dfPCPI.set_index('Date')

dfPCPI_Rel = dfPCPI.apply(lambda x: x / x[0])

dfPCPI_Small = dfPCPI.iloc[8:].copy()
dfPCPI_SmRel = dfPCPI_Small.apply(lambda x: x / x[0])

dfPCPI_SmRel.plot()

fig, ax = plt.subplots(1, 2)

ax0 = ax[0].plot(dfPCPI_Rel, '-', label='a')
ax1 = ax[1].plot(dfPCPI_SmRel, '-', label='test1')

ax[0].legend()

for x in fig.axes:
    for label in x.get_xticklabels():
        label.set_rotation(45)

ax[1].xaxis.set_major_locator(ticker.MultipleLocator(2))

plt.show()

Tags: csvhttpsimport绘图fordatematplotlibas
2条回答

pyplot中的图例引用了axis实例。因此,如果希望多个绘图有自己的图例,则需要为每个轴调用legend()。对你来说

ax[0].legend()
ax[1].legend()

此外,在调用plot()时,您可能希望在每次plot()调用中使用关键字label,以便为每个图例项提供一个标签。在

您应该尝试fig.legend()而不是plt.legend()

相关问题 更多 >