How to force matplotlib to show values on x-axis as integers

Viewed 20903

Code like this:

plt.ticklabel_format(style='plain', axis='x', useOffset=False)
plt.plot(range(1, 3), logger.acc)
plt.xlabel("Epochs")
plt.ylabel("Accuracy")
plt.show()

Produces a result like this:
plot

I want the x axis to only have whole integer numbers. There should be a simple flag for this, but i can't find it.

2 Answers

Just use the following where you set the xticks as the integer values generated by the range() function. You can replace the numbers with whatever range you are plotting within

plt.xticks(range(1,3))

You may use a MultipleLocator with the base set to 1.

import matplotlib.pyplot as plt
import matplotlib.ticker as mticker

class logger():
    acc = [ .26, .36]

plt.ticklabel_format(style='plain', axis='x', useOffset=False)
plt.plot(range(1, 3), logger.acc)
plt.gca().xaxis.set_major_locator(mticker.MultipleLocator(1))
plt.xlabel("Epochs")
plt.ylabel("Accuracy")
plt.show()

enter image description here

Related