How to force Matplotlib to show the values on X-axis as integers?

PythonServer Side ProgrammingProgramming

To force matplotlib to show the values on X-axis as integers, we can take the following steps −

  • Set the figure size and adjust the padding between and around the subplots.
  • Create two lists, x and y, of data points.
  • Plot x and y using plot() method.
  • Make a new list for only integers tick on X-axis. Use math.floor() and math.ceil() to remove the decimals and include only integers in the list.
  • Set x and y labels.
  • Set the title of the figure.
  • To display the figure, use show() method.

Example

import math
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

y = [0.17, 1.17, 2.98, 3.15, 4.11, 5.151]
x = [1.0, 1.75, 2.90, 3.15, 4.50, 5.50]

plt.plot(x, y)

new_list = range(math.floor(min(x)), math.ceil(max(x))+1)
plt.xticks(new_list)

plt.xlabel("X-axis ")
plt.ylabel("Y-axis ")

plt.title("Only Integers on the X-axis")

plt.show()

Output

raja
Published on 08-Jul-2021 11:06:43
Advertisements