gpt4 book ai didi

python - 滚动平均图例标签

转载 作者:行者123 更新时间:2023-12-04 04:01:42 25 4
gpt4 key购买 nike

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

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

请注意,日期时间对象是数据帧的索引。

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

enter image description here

最佳答案

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

关于python - 滚动平均图例标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62956420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com