Search code examples
pythonmatplotlibbar-chartaxis-labels

Position of Matplotlib Pyplot bar chart labels not consistent with nan values


I'm plotting bar charts of data that contains missing values (np.nan). It seems as though when the np.nan value appears in the last category, the x-axis ticks are positioned differently than when there are no np.nans or when the NaN values are in a different position.

import numpy as np
import matplotlib.pyplot as plt

%matplotlib inline

years = np.array([2011, 2012, 2013, 2014, 2015])
x = np.arange(len(years))
y1 = np.array([ 29.,  10.,  16.,  29., np.nan])
y2 = np.array([ 29.,  10.,  np.nan,  29., 16.])
y3 = np.array([ np.nan,  29., 29.,  10.,  16.])

f = plt.figure(figsize=(4,6))

ax = f.add_subplot(311)
ax.bar(x, y1, align='center')
ax.set_xticks(x)
ax.set_xticklabels(years)

ax = f.add_subplot(312)
ax.bar(x, y2, align='center')
ax.set_xticks(x)
ax.set_xticklabels(years)

ax = f.add_subplot(313)
ax.bar(x, y3, align='center')
ax.set_xticks(x)
ax.set_xticklabels(years)

plt.show()

Output in jupyter notebook

Ideally, I would like the x-axis labels to be in the same place, regardless of whether there are NaN values in the data.


Solution

  • If you need a specific range on the plot, you can just set it explicitly. After each block add, e.g.

    ax.set_xlim(-0.5, years.size - 0.5)
    

    enter image description here