Skip to content Skip to sidebar Skip to footer

Matplotlib Bar Chart For Negative Numbers Going Above X-axis

I am trying to make a bar chart of negative values where the baseline x-axis is at -10 instead of 0 and the values, because they are all -10

Solution 1:

Following https://matplotlib.org/gallery/ticks_and_spines/custom_ticker1.html example, you can also do like this:

from matplotlib.ticker import FuncFormatter
defneg_tick(x, pos):
    return'%.1f' % (-x if x else0) # avoid negative zero (-0.0) labels

formatter = FuncFormatter(neg_tick)
fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(formatter)
plt.bar(range(len(vals)), [-v for v in vals]) # or -numpy.asarray(vals)# or, let Python enumerate bars:# plt.bar(*zip(*enumerate(-v for v in vals)))
plt.show()

You cannot not "fake" data. Bar charts plot bars up for positive data and down for negative. If you want things differently, you need to trick bar chart somehow.

enter image description here

IMO, the above solution is better than https://stackoverflow.com/a/11250884/8033585 because it does not need the trick with drawing canvas, changing labels, etc.


If you do want to have "reverted" bar length (as it is in your example), then you can do the following:

from matplotlib.ticker import FuncFormatter
import numpy as np

# shifted up:
vals = np.asarray(vals)
minval = np.amin(vals)
minval += np.sign(minval) # "add"1 so that "lowest" bar is still drawn
def neg_tick(x, pos):
    return '%.1f' % (x + minval if x != minval else 0)

formatter = FuncFormatter(neg_tick)
fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(formatter)
plt.bar(*zip(*enumerate(-minval + vals)))
plt.show()

enter image description here

Solution 2:

Try matplotlib.axes.Axes.invert_yaxis

from matplotlib import pyplot as plt
vals = [-4, -6, -8, -6, -5]
plt.bar(range(len(vals)), vals)

enter image description here

fig, ax1 = plt.subplots(1,1)
ax1.bar(range(len(vals)), vals)
ax1.invert_yaxis()

enter image description here

Post a Comment for "Matplotlib Bar Chart For Negative Numbers Going Above X-axis"