Tim
Tim

Reputation: 99498

How to prevent matplotlib from showing decimal years in horizontal axis

import matplotlib.pyplot as plt
import matplotlib.path as mpath
import numpy as np

# Data for plotting
t = [2013, 2014, 2015, 2016, 2017]
s = [12.92, 14.19, 15.39, 15.72, 16.03]

fig, ax = plt.subplots()
ax.plot(t, s, 'o', markersize=15)
ax.set(xlabel='year', ylabel='Revenue (billion dollars)',
       title='Revenue Growth')
fig.savefig("test.png")
plt.show()

The output is here, but the horizontal axis represents year; how can I stop it from showing decimal years?

enter image description here

Upvotes: 2

Views: 1962

Answers (2)

jackotonye
jackotonye

Reputation: 3853

 from matplotlib.ticker import FormatStrFormatter

 fig, ax = plt.subplots()
 ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))

Upvotes: 1

Arya11
Arya11

Reputation: 568

a possible solution is converting your array to numpy array and passing it as string:

ax.plot(np.asarray(t).astype(str), s, 'o', markersize=15)

Upvotes: 2

Related Questions