user2501498
user2501498

Reputation: 65

How can I set x-axis tick marks with only whole numbers?

I've been using host to plot my graphs, and I would like to take decimal numbers off from my x axis. My code below is kinda simplified, it represents what I need tho. I want the x-range to be exactly the same as the RUNS vector. Thanks a lot.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot
import numpy as np
import mpl_toolkits.axisartist as AA
import matplotlib.gridspec as gridspec

gs = gridspec.GridSpec(2, 1, height_ratios=[1, 1])

RUNS = [1,2,3,4,5]
NV = [26.3, 28.4, 28.5, 28.45, 28.5]

host = host_subplot(gs[0], axes_class = AA.Axes)
host.set_xlabel("Iteration")
host.set_ylabel("Stress (MPa)")
sv, = host.plot(RUNS,NV, marker = 'o', color = 'gray')

plt.grid(True)
plt.show()

Upvotes: 4

Views: 12499

Answers (2)

captain_M
captain_M

Reputation: 287

You can use MaxNLocator to set major tick labels to integers as well, but its not quiet as simple.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot
import numpy as np
import mpl_toolkits.axisartist as AA
import matplotlib.gridspec as gridspec
from matplotlib.ticker import MaxNLocator  ## Import MaxNLocator

gs = gridspec.GridSpec(2, 1, height_ratios=[1, 1])

RUNS = [1,2,3,4,5]
NV = [26.3, 28.4, 28.5, 28.45, 28.5]



host = host_subplot(gs[0], axes_class = AA.Axes)
host.set_xlabel("Iteration")
host.set_ylabel("Stress (MPa)")

x_ax = host.axes.get_xaxis()  ## Get X axis
x_ax.set_major_locator(MaxNLocator(integer=True))  ## Set major locators to integer values

sv, = host.plot(RUNS,NV, marker = 'o', color = 'gray')

plt.grid(True)
plt.show()

Upvotes: 9

Loïc Séguin-C.
Loïc Séguin-C.

Reputation: 1886

You can set the tick labels explicitly before you show the plot:

plt.xticks(RUNS)

Upvotes: 6

Related Questions