I have designed a subplot using matplotlib
. I am trying to reverse the xticks
of the plot. Please see the sample code-
import numpy as np
import matplotlib.pyplot as plt
# generate the data
n = 6
y = np.random.randint(low=0, high=10, size=n)
x = np.arange(n)
# generate the ticks and reverse it
xticks = range(n)
xticks.reverse()
# plot the data
plt.figure()
ax = plt.subplot(111)
ax.bar(x, y)
print xticks # prints [5, 4, 3, 2, 1, 0]
ax.set_xticks(xticks)
plt.show()
Please see below the generated plot-
Please pay attention to the xticks
. Even though, ax.set_xticks(xticks)
is used but the xticks
haven't changed. Am I missing some function call to rerender the plot?
Below is the system information-
matplotlib.__version__
'2.1.1'
matplotlib.__version__numpy__
'1.7.1'
python --version
Python 2.7.15rc1
Please note that I just want to reverse the ticks and do not want to invert axis.
With ax.set_xticks
, you are currently specifying tick positions which is invariant to the order of the list. Either you pass [0, 1, 2, 3, 4, 5]
or you pass [5, 4, 3, 2, 1, 0]
. The difference will not be noticed in the ticks. What you instead want is to have reversed ticklabels for which you should do set_xticklabels(xticks[::-1])
. There are two ways to do it:
Way 1
Use plt.xticks
where the first argument specifies the location of the ticks and the second arguments specifies the respective ticklabels. Specifically, xticks
will provide the tick positions and xticks[::-1]
will label your plot with reversed ticklabels.
xticks = range(n)
# plot the data
plt.figure()
ax = plt.subplot(111)
ax.bar(x, y)
plt.xticks(xticks, xticks[::-1])
Way 2 using ax
where you need set_xticklabels
to get what you want
ax.set_xticks(xticks)
ax.set_xticklabels(xticks[::-1])
Use:
# generate the data
n = 6
y = np.random.randint(low=0, high=10, size=n)
x = np.arange(n)
# generate the ticks and reverse it
xticks = range(n)
# xticks.reverse()
# plot the data
plt.figure()
ax = plt.subplot(111)
ax.bar(x, y)
# print xticks # prints [5, 4, 3, 2, 1, 0]
ax.set_xticklabels(xticks[::-1]) # <- Changed
plt.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With