[ACCEPTED]-How to add a line on a pandas bar plot in matplotlib?-pandas
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 : ax = df[['price','cost']].plot(kind = 'bar',stacked = True,color = ['grey','navy']) In : ax.get_children() Out: <matplotlib.patches.Rectangle at 0x16f2aba8> In : ax.get_children().get_width() Out: 0.5 In : ax.get_children().get_bbox() Out: Bbox('array([[ 0.25, 0. ],\n [ 0.75, 22.5 ]])') In : plt.plot(df.index+0.5, df['net'],color = 'orange',linewidth=2.0)
I 8 do the
.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