0

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')
vlemaistre
  • 3,301
  • 13
  • 30
  • 1
    You would want to convert your strings to actual dates. Then matplotlib will automatically show no more than 10 dates on the axis. In addition it will make sure the points are correctly spaced (e.g. in case they are not equidistant). – ImportanceOfBeingErnest May 23 '19 at 21:04
  • Possible duplicate of [Cleanest way to hide every nth tick label in matplotlib colorbar?](https://stackoverflow.com/questions/20337664/cleanest-way-to-hide-every-nth-tick-label-in-matplotlib-colorbar) – Heath Raftery May 23 '19 at 21:11

1 Answers1

1

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

Juan C
  • 5,846
  • 2
  • 17
  • 51
  • Thanks this helped me ! But the first part of your code doesen't produce the graphic you put. I had to change the line to : plt.xticks(sr.index[::4], sr.index[::4]) to make it work. Did it work without it on your end ? – vlemaistre May 24 '19 at 06:26
  • That's weird, it worked for me like I posted it in my end. Maybe different matplotlib versions? – Juan C May 24 '19 at 19:36