[英]pandas DataFrame how to mix bar and line plots with different scales
I am trying to get pandas to overlay a bar plot and a line plot.我试图让熊猫覆盖条形图和线图。 The two series have different scales so I want the values to be plotted on two "y" axes.
这两个系列具有不同的比例,因此我希望将值绘制在两个“y”轴上。 I cannot get pandas to show the "bar" and "line" plots together.
我无法让熊猫一起显示“条形”和“线形”图。
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"])
This gives the DataFrame这给了 DataFrame
Release Hold
2014 1212 231
2015 9283 624
2016 11734 943
2017 12452 1037
2018 16766 1037
2019 120 113
Now if I try to plot the "Release" as a bar chart and the "Hold" column as lines with twin axes I get only the line.现在,如果我尝试将“发布”绘制为条形图,将“保持”列绘制为带有双轴的线,我只会得到这条线。
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')
If however I plot both as lines .但是,如果我将两者都绘制为线。 Both the values show up.
两个值都显示出来。 I am wondering how to make the bars and lines show up on the same plot.
我想知道如何使条形和线条显示在同一个图上。 I am using pandas version '0.16.2' and matplotlib version '1.3.1'.
我正在使用 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')
This can be done entirely with pandas , including labels and legend:这可以完全使用pandas完成,包括标签和图例:
import pandas as pd # v 1.1.3
df = pd.DataFrame(data=[(1212,231), (9283,624), (11734,943), (12452,1037), (16766,1037), (120,113)],
index=[2014, 2015, 2016, 2017, 2018, 2019], columns=['Release', 'Hold'])
ax = df.plot.bar(y='Release', ylabel='Release', figsize=(8, 5))
df.plot(y='Hold', c='k', ax=ax, use_index=False, secondary_y=True, mark_right=False)
ax.right_ax.set_ylabel('Hold');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.