vlemaistre
vlemaistre

Reputation: 3331

How to plot evenly spaced values on the x axis while plotting using matplotlib

I have a Series with more than 100 000 rows that I want to plot. I have problem with the x-axis of my figure. Since my x-axis is made of several dates, you can't see anything if you plot all of them.

How can I choose to show only 1 out of every x on the x-axis ?

Here is an example of a code which produces a graphic with an ugly x-axis :

sr = pd.Series(np.array(range(15)))
sr.index = [ '2018-06-' + str(x).zfill(2) for x in range(1,16)]
Out : 
2018-06-01     0
2018-06-02     1
2018-06-03     2
2018-06-04     3
2018-06-05     4
2018-06-06     5
2018-06-07     6
2018-06-08     7
2018-06-09     8
2018-06-10     9
2018-06-11    10
2018-06-12    11
2018-06-13    12
2018-06-14    13
2018-06-15    14

fig = plt.plot(sr)
plt.xlabel('Date')
plt.ylabel('Sales')

Upvotes: 0

Views: 3910

Answers (1)

Juan C
Juan C

Reputation: 6132

Using xticks you can achieve the desired effect:

In your example:

sr = pd.Series(np.array(range(15)))
sr.index = [ '2018-06-' + str(x).zfill(2) for x in range(1,16)]
fig = plt.plot(sr)
plt.xlabel('Date')
plt.xticks(sr.index[::4]) #Show one in every four dates
plt.ylabel('Sales')

Output:

enter image description here

Also, if you want to set the number of ticks, instead, you can use locator_params:

sr.plot(xticks=sr.reset_index().index)
plt.locator_params(axis='x', nbins=5) #Show five dates
plt.ylabel('Sales')
plt.xlabel('Date')

Output:

enter image description here

Upvotes: 1

Related Questions