pandas DataFrame如何混合不同比例的条形图和线图

2024-04-21

我试图让 pandas 覆盖条形图和线图。这两个系列具有不同的比例,因此我希望将值绘制在两个“y”轴上。我无法让 pandas 一起显示“条形图”和“线形图”。

from pandas import DataFrame

df_eg = DataFrame()
df_eg=DataFrame(data=[(1212,231),(9283,624),(11734,943),(12452,1037),(16766,1037),(120,113)],index=[2014,2015,2016,2017,2018,2019],columns=["Release","Hold"])

这给出了数据框

       Release  Hold
2014    1212    231
2015    9283    624
2016    11734   943
2017    12452   1037
2018    16766   1037
2019    120     113

现在,如果我尝试将“释放”绘制为条形图,将“保持”列绘制为双轴线,我只能得到这条线。

fig, ax = plt.subplots()
ax2 = ax.twinx()
plt.hold(False)
df_eg["Release"].plot(ax=ax,kind="bar")
df_eg["Hold"].plot(ax=ax2, style='r-', secondary_y=True)
ax.legend(loc='best')

然而,如果我将两者都绘制为线条。两个值都会显示。 我想知道如何使条形图和线条显示在同一个图上。我正在使用 pandas 版本“0.16.2”和 matplotlib 版本“1.3.1”。

fig, ax = plt.subplots()
ax2 = ax.twinx()
plt.hold(False)
df_eg["Release"].plot(ax=ax,kind="line")
df_eg["Hold"].plot(ax=ax2, style='r-', secondary_y=True)
ax.legend(loc='best')

这能解决您的问题吗?

fig, ax = plt.subplots()
ax2 = ax.twinx()
ax.bar(df_eg.index, df_eg["Release"], color=(190/255,190/255,190/255,0.7), label='Release')
ax2.plot(df_eg.index, df_eg["Hold"], color='green', label='Hold')
ax.set_xticklabels(df_eg.index)
ax.legend(loc='best')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

pandas DataFrame如何混合不同比例的条形图和线图 的相关文章

随机推荐