【问题标题】:pandas DataFrame how to mix bar and line plots with different scalespandas DataFrame如何混合不同比例的条形图和线图
【发布时间】:2018-06-04 10:28:11
【问题描述】:

我试图让 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"])

这给出了 DataFrame

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

现在,如果我尝试将“Release”绘制为条形图,将“Hold”列绘制为带有双轴的线条,我只会得到线条。

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

但是,如果我将两者都绘制为 lines 。两个值都显示。 我想知道如何使条形图和线条出现在同一个图上。我正在使用 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')

【问题讨论】:

标签: python pandas matplotlib plot


【解决方案1】:

这能解决您的问题吗?

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

【讨论】:

  • 如何结合传说?
  • @rodrigo-silveira 查看我的回答。如果您想将图例放在其他地方,您需要导入 matplotlib 并运行类似这样的内容:ax.legend().remove(); plt.gcf().legend(loc=(0.12, 0.82)) 这有点 hacky,但到目前为止我还没有找到更好的方法。
【解决方案2】:

这可以完全用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');

【讨论】:

  • 它对我有用...谢谢!!
猜你喜欢
  • 2016-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多