滚动平均图例标签

2024-09-29 21:54:48 发布

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

我试图在双轴图上绘制滚动平均值。但是,我无法正确创建图例。有什么建议吗

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

temp看起来是这样的:

             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


Tags: alphaplotnantemplabelbetalabs图例
1条回答
网友
1楼 · 发布于 2024-09-29 21:54:48

我刚刚添加了另一个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)

相关问题 更多 >

    热门问题