Mark Mark - 1 month ago 5x
Python Question

Shifting x labels in Matplotlib, Ipython

I'm trying to make three charts in one output with matplotlib in an ipython notebook. When I output the chart is correct for the fisrt one, but on the second and third the x labels are messed up, and there are more cells in the second and third chart. I want them all to be uniform.

fig, axs = plt.subplots(1,3, figsize=(15,10))
ax0, ax1, ax2 = axs.flat

labels = ['Asian', 'Black', 'Hispanic', 'Unknown', 'White']

day1M = day1df[(day1df.Gender == "M")]
day15M = day15df[(day15df.Gender == "M")]
day30M = day30df[(day30df.Gender == "M")]

grouped1 = day1M.groupby("Race").size()
grouped15 = day15M.groupby("Race").size()
grouped30= day30M.groupby("Race").size()

x = range(len(grouped1)), grouped1)
ax0.set_xticklabels(labels, rotation='vertical')

x = range(len(grouped15)), grouped15)
ax1.set_xticklabels(labels, rotation='vertical')

x = range(len(grouped30)), grouped30)
ax2.set_xticklabels(labels, rotation='vertical')

and here is what the current output looks like



You should almost never use set_xticklabels because it is (under the hood) just using a FixedFormatter to tick labels. If you do not also set the locator to be FixedLocator, then the tick labels are applied, in sequence, to the ticks.

As of mpl 1.5, there is a tick_label kwarg to bar (docs) that will automatically label your bars. I suspect you want to do something like, data, tick_label=labels, align='center')