X axis weirdness with DataFrame.plot(kind='bar') · Issue #11465 · pandas-dev/pandas (original) (raw)

I encountered this issue when plotting some vertical axes spans on the same axes as a bar plot. Some example code is below to reproduce the issue. When using either scatter or line plots, the spans show up where they are supposed to, but the bar plot is off.

Digging a little deeper, I found that the plot call is setting the xticks to a zero-indexed array with a step size of one while setting the tick labels to the correct values.
If you specify the x ticks in the call to the bar plot, the spans are plotted at the correct position, but the bars are plotted from the same 0-indexed, singly incrementing array.

import pandas as pd import numpy as np import matplotlib.pyplot as plt

spans = pd.DataFrame(np.array([[10,15]]), columns=['left','right']) datdf = pd.DataFrame(zip(np.random.rand(15),np.random.rand(15)/10), columns=['foo','bar'], index=np.arange(5,20))

fig, axes = plt.subplots(nrows=3, ncols=1)

for a, ax in enumerate(axes): for i, row in spans.iterrows(): ax.axvspan(row['left'],row['right'],color=(0,0,0,.5),zorder=0)

datdf.plot(ax=axes[0], kind='line') # all is good datdf.plot(ax=axes[1], kind='bar', stacked=True) # span is wrong datdf.plot(ax=axes[2], kind='bar', stacked=True, xticks=datdf.index.values) #bars are wrong

ticks = [] ticklabs = []

for a, ax in enumerate(axes): print a, print zip(ax.xaxis.get_ticklocs(), [lab.get_text() for lab in ax.xaxis.get_ticklabels()])

image

axes 0
[(5.0, u''), (10.0, u''), (15.0, u''), (20.0, u''), (25.0, u''), (30.0, u''), (35.0, u'')]
axes 1
[(0, u'5'), (1, u'7'), (2, u'9'), (3, u'11'), (4, u'13'), (5, u'15'), (6, u'17'), (7, u'19'), (8, u'21'), (9, u'23'), (10, u'25'), (11, u'27'), (12, u'29'), (13, u'31'), (14, u'33')]
axes 2
[(5, u'5'), (7, u'7'), (9, u'9'), (11, u'11'), (13, u'13'), (15, u'15'), (17, u'17'), (19, u'19'), (21, u'21'), (23, u'23'), (25, u'25'), (27, u'27'), (29, u'29'), (31, u'31'), (33, u'33')]