[ACCEPTED]-How to add a line on a pandas bar plot in matplotlib?-pandas

Score: 10

Update: this will be fixed in the upcoming 21 0.14 release (and your code above will just 20 work), for older pandas releases my answer 19 below can be used as a workaround.

The problem 18 you encounter is that the xaxis labels you 17 see on the bar chart do not correspond exactly 16 with the actual underlying coordinates that 15 matplotlib uses.
Eg with the default `bar` plot 14 in matplotlib, the first rectangle (first 13 bar with label 0) will be plotted on x-coordinates 12 of 0 to 0.8 (bar width of 0.8). So if you 11 want to plot a point or line in the middle of 10 this, this should have x-coordinate of 0.4, and 9 not 0!

To solve this in your case, you can do:

``````In [3]: ax = df[['price','cost']].plot(kind = 'bar',stacked = True,color = ['grey','navy'])

In [4]: ax.get_children()[3]
Out[4]: <matplotlib.patches.Rectangle at 0x16f2aba8>

In [5]: ax.get_children()[3].get_width()
Out[5]: 0.5

In [6]: ax.get_children()[3].get_bbox()
Out[6]: Bbox('array([[  0.25,   0.  ],\n       [  0.75,  22.5 ]])')

In [7]: plt.plot(df.index+0.5, df['net'],color = 'orange',linewidth=2.0)
``````

I 8 do the `ax.get_children()[3].get_width()` and `.get_bbox()` to inspect the actual width 7 and coordinates of the bars in your plot, as 6 pandas doesn't seem to use the default values 5 of matplotlib (the value of 0.5 actually 4 comes from 0.25 (offset from y-axis to start 3 first bar) + 0.5/2 (half of the width)).

So 2 what I actually did was changing `df['net'].plot(use_index = True)` to `plt.plot(df.index + 0.5, df['net'])`.

This 1 gives me:

More Related questions