线条没有显示在条形图上

时间:2018-04-18 07:54:28

标签: 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'我得到三行,如果我改变了种类=' line'善良=' bar'我有三个酒吧......

2 个答案:

答案 0 :(得分:4)

根据其性质,条形图具有分类的x轴。但是线图具有连续的x轴,除非你强行使用它。

所以,你可以强迫你的岁月成为字符串并获得你想要的东西:

from io import StringIO
from matplotlib import pyplot
import pandas

df = pandas.read_table(StringIO("""\
year   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
"""), sep='\s+', dtype={'year': str}).set_index('year')

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

enter image description here

答案 1 :(得分:4)

问题是您的条形被绘制为类别而您的线条在连续轴上绘制 - 所以当条形的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