python - 线条不显示在条形图上

标签 python python-3.x pandas dataframe matplotlib

我正在尝试在条形图上绘制一条线。

这是我的数据框:

       meh  fiches     ratio
2007  1412    1338  0.947592
2008  1356    1324  0.976401
2009  1394    1298  0.931133
2010  1352    1275  0.943047
2011  1398    1325  0.947783
2012  1261    1215  0.963521
2013  1144     845  0.738636
2014  1203    1167  0.970075
2015  1024    1004  0.980469
2016  1197    1180  0.985798

当我运行这两行时,我得到:

ax = graph[['meh', 'fiches']].plot(kind='bar', color=['#666666','#999999'])
graph[['ratio']].plot(kind='line',color='red', linestyle='-', secondary_y=True, ax=ax)

enter image description here

但是,如果我删除 kind='bar' 我会得到三行,如果我将 kind='line' 更改为 kind='bar' 我会得到三个条...

最佳答案

问题是您的条形图是按类别绘制的,而您的线是绘制在连续轴上的 - 因此虽然您的条形图的 x 位置看起来好像是年份,但它们实际上是 0 到 9 的值。要获得围绕这一点,您可以在使用 ax.get_xticks() 绘制比率时指定 x 值:

import io

import pandas as pd
import matplotlib.pyplot as plt

data = io.StringIO('''       meh  fiches     ratio
2007  1412    1338  0.947592
2008  1356    1324  0.976401
2009  1394    1298  0.931133
2010  1352    1275  0.943047
2011  1398    1325  0.947783
2012  1261    1215  0.963521
2013  1144     845  0.738636
2014  1203    1167  0.970075
2015  1024    1004  0.980469
2016  1197    1180  0.985798''')

graph = pd.read_csv(data, sep='\s+')

ax = graph[['meh', 'fiches']].plot(kind='bar', color=['#666666','#999999'])
graph[['ratio']].plot(x=ax.get_xticks(), kind='line',color='red', linestyle='-', secondary_y=True, ax=ax)

plt.show()

这表明:

Graph with line on bars

关于python - 线条不显示在条形图上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49894161/

相关文章:

python - 带有用于自定义作业的附加线程的 CherryPy

python - 我正在尝试使用 numpy 模块创建和实现一个在 Python 中识别数据集中异常值的函数,不断获取 'ValueError'

python - 将 3D 数组 reshape 为 2D 数组以生成 DataFrame : keep track of indices to produce column names

python - 如何为不同的实现提取学习到的 ML 模型?

python - 将 Count 连接到 pandas 中的原始 DataFrame

python - 使用 Python 测试 AWS lambda

python - 如何扩展模型用户?

python - 如何将 functools.singledispatch 与实例方法一起使用?

python - pandas - 为什么我无法使用 Pandas 的 "skiprows"参数跳过行

python - 如何选择 Pandas 中的行范围?