熊猫辅助轴

2024-01-25

我有以下数据框:

    Date        A           B
0   2017-05-31  17453139    5.865738
1   2017-06-30  17425164    5.272728
2   2017-07-31  17480789    4.843094

当我运行这个时:

df.plot(x='Date', y='A')
df.B.plot(secondary_y=True)

我收到以下错误:

> appdata\local\programs\python\python36\lib\site-packages\pandas\plotting\_timeseries.py
> in format_dateaxis(subplot, freq, index)
>     335             TimeSeries_TimedeltaFormatter())
>     336     else:
> --> 337         raise TypeError('index type not supported')
>     338 
>     339     pylab.draw_if_interactive()
> 
> TypeError: index type not supported

And my graph looks like this underneath the error (blue and red should overlap): Blue and red should overlap


Use secondary_y in pandas.DataFrame.plot https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html:

ax = df.plot('Date', 'A')
df.plot('Date', 'B', secondary_y=True, ax=ax)

更简洁地说:

ax = df.plot(x='Date', y=['A', 'B'], secondary_y='B', figsize=(8, 5))

# move the legend for each y axis
ax.legend(bbox_to_anchor=(1.05, 0.53), loc='center left', frameon=False)
ax.right_ax.legend(bbox_to_anchor=(1.05, 0.47), loc='center left', frameon=False)

(可选)使用ax.twinx()

ax = df.plot('Date','A')
ax1 = ax.twinx()
df.plot('Date','B',ax=ax1, color='r')

Output:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

熊猫辅助轴 的相关文章

随机推荐