滚动平均值图例标签

时间:2020-07-17 14:47:21

标签: python pandas dataframe

我正在尝试在双轴图上绘制滚动平均值。但是,我无法正确创建图例。有指针吗?

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()

# df6 = t100df5.rolling(window=12).mean()
lns1 = ax1.plot(
     df6,
    label = ['Alpha', 'Beta'],         # how do I add 'Beta' label correctly?
    linewidth = 2.0)


lns2 = ax2.plot(temp,
                label = 'Dollars',
                color='black')

lns = lns1+lns2
labs = [l.get_label() for l in lns]
L = ax1.legend(lns, labs, loc = 0, frameon = True)

df6看起来像这样:

          Alpha    Beta
TIME        
1990-01-01  NaN     NaN
1990-02-01  NaN     NaN
1990-03-01  NaN     NaN
1990-04-01  NaN     NaN
1990-05-01  NaN     NaN
...     ...     ...
2019-08-01  10.012447   8.331901
2019-09-01  9.909044    8.263813
2019-10-01  9.810155    8.185539
2019-11-01  9.711690    8.085016
2019-12-01  9.619968    8.03533

温度看起来像这样:

             Dollars
date    
1994-01-01  NaN
1994-02-01  NaN
1994-03-01  225.664248
1994-04-01  217.475670
1995-01-01  216.464499
...     ...
2018-04-01  179.176545
2019-01-01  177.624369
2019-02-01  178.731035
2019-03-01  176.624608
2019-04-01  177.357060

请注意,datetime对象是数据帧的索引。

如何为下图添加带有适当标签的图例?黑线来自temp,其他两行均来自df6。

enter image description here

1 个答案:

答案 0 :(得分:0)

我刚刚添加了另一个ax1.plot语句,如下所示:

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()

lns1 = ax1.plot(
     df6.index, df6.Alpha
    label = 'Alpha',
    linewidth = 2.0)

lns1_5 = ax1.plot(df6.index, df6.Beta, label = 'Beta')

lns2 = ax2.plot(temp,
                label = 'Dollars',
                color='black')

lns = lns1+lns1_5+lns2
labs = [l.get_label() for l in lns]
L = ax1.legend(lns, labs, loc = 0, frameon = True)