Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 348
user2762996 Avatar asked Sep 07 '18 21:09

user2762996


People also ask

How do I show all the values on the X-axis in MatPlotLib?

Use xticks() method to show all the X-coordinates in the plot. Use yticks() method to show all the Y-coordinates in the plot. To display the figure, use show() method.

How do I change the X-axis values in MatPlotLib?

The xticks() function in pyplot module of the Matplotlib library is used to set x-axis values. List of xticks locations. Passing an empty list will remove all the xticks.

How do I get rid of scientific notation in MatPlotLib?

Using ticklabel_format() method with style='plain'. If a parameter is not set, the corresponding property of the formatter is left unchanged. Style='plain' turns off scientific notation.

How do I change my axis number in MatPlotLib?

To change the range of X and Y axes, we can use xlim() and ylim() methods.


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))
like image 77
Sheldore Avatar answered Nov 10 '22 00:11

Sheldore


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

like image 43
ImportanceOfBeingErnest Avatar answered Nov 10 '22 01:11

ImportanceOfBeingErnest