我试图在同一图中绘制一条线和面积图,其中一个图例显示了线条和区域样式。不幸的是,下面的代码只生成线条,而图例中没有区域。
是否可以在同一个图例中获得两条线和区域?如果没有,我可以在同一图上获得面积图的第二个图例吗?
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.abs(np.random.randn(6,4)), index=dates, columns=list('ABCD'))
f, ax = plt.subplots()
df[['A','B']].plot(ax=ax, figsize=(10,5))
df[['C','D']].plot(kind='area',ax=ax, figsize=(10,5))
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
答案 0 :(得分:2)
您可以通过以下方式完成此操作:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import patches
# data
dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.abs(np.random.randn(6,4)),
index=dates,
columns=list('ABCD'))
# plot
f, ax = plt.subplots()
# lines A and B
lineA, = ax.plot(df.index, df['A'], color = 'black', label = 'A')
lineB, = ax.plot(df.index, df['B'], color = 'green', label = 'B')
# stacked plots
ax.fill_between(df.index, 0, df['C'], color = 'blue',label = 'C')
ax.fill_between(df.index, df['C'], df['D'], color = 'red', label = 'D')
# Labels for both stacked plots
blue_patch = patches.Patch(color='blue', label='C')
red_patch = patches.Patch(color='red', label='D')
# legend
ax.legend(handles = [lineA, lineB, blue_patch, red_patch],
loc='center left', bbox_to_anchor=(1, 0.5))
# show the final plot
f.show()