Matplotlib barplot, general way to set xticklabels in the middle of a panel
The following code generates a barcode with xticklabels centered for each bar. However, scaling the x-axis, changing the number of stripes, or changing the width of the stripe changes the position of the labels. Is there a general way to combat this behavior?
# This code is a hackish way of setting the proper position by trial
# and error.
import matplotlib.pyplot as plt
import numpy as np
y = [1,2,3,4,5]
# adding 0.75 did the trick but only if I add a blank position to `xl`
x = np.arange(0,len(y)) + 0.75
xl = ['', 'apple', 'orange', 'pear', 'mango', 'peach']
fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(x,y,0.5)
ax.set_xticklabels(xl)
# I cannot change the scaling without changing the position of the tick labels
ax.set_xlim(0,5.5)
Proposed and working solution:
import matplotlib.pyplot as plt
import numpy as np
y = [1,2,3,4,5]
x = np.arange(len(y))
xl = ['apple', 'orange', 'pear', 'mango', 'peach']
fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(x,y,0.5, align='center')
ax.set_xticks(x)
ax.set_xticklabels(xl)
source to share
So the problem is that you are only calling ax.set_xticklabels
. This fixes the labels, but tick positions are still processed AutoLocator
, which will add / remove ticks when the axis limits change.
Thus, you also need to fix the tick positions:
ax.set_xticks(x)
ax.set_xticklabels(xl)
By calling set_xticks
, the element AutoLocator
is replaced under the hood FixedLocator
.
And then you can center the bars to make it more attractive (optional):
ax.bar(x, y, 0.5, align='center')
source to share