简体   繁体   English

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

[英]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')

pandas_plot_without_bar_shwoing_up

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')

在此处输入图片说明

Does this solve your problem?这能解决您的问题吗?

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')

最终剧情

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');

pandas_line_bar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM