Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Line doesn't show over barplot

I'm trying to plot a line over a bar chart.

Here is my dataframe :

       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

When I run these two lines I get :

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

However if I remove kind='bar' I get three lines and if I change kind='line' for kind='bar' I get three bars...

like image 201
Martin B Avatar asked Apr 18 '18 07:04

Martin B


2 Answers

The issue is your bars are plotted as categories while your line is plotted on a continuous axis - so while the x positions of your bars appear as though they are the years, they're actually the values 0 to 9. To get around this, you can specify the x values when you plot the ratios using ax.get_xticks():

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

This shows:

Graph with line on bars

like image 108
asongtoruin Avatar answered Nov 07 '22 01:11

asongtoruin


Bar plots, by their nature, have categorical x-axes. But line plots have continuous x-axes, unless you force it otherwise.

So, you can force your years to be strings and get what you want:

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

like image 28
Paul H Avatar answered Nov 07 '22 01:11

Paul H