我无法将图例显示在子图上,这些图显示得很好,并不能采用我应用的其他格式。我想念什么?
如果仅对数据框进行绘制,它将显示图例。如果我在子图的图上添加标签,它将为所有三条线分配该标签。
这是图像。情节与子情节
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()
答案 0 :(得分:0)
您应该尝试使用fig.legend()
而不是plt.legend()
答案 1 :(得分:0)
pyplot中的图例指的是轴实例。因此,如果要让多个图具有自己的图例,则需要为每个轴调用legend()。就您而言
ax[0].legend()
ax[1].legend()
此外,在调用plot()时,您可能希望在每个plot()调用中使用关键字标签,以便为每个图例条目都有一个标签。