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')
2
  • 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). Commented May 23, 2019 at 21:04
  • Possible duplicate of Cleanest way to hide every nth tick label in matplotlib colorbar? Commented May 23, 2019 at 21:11

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 ?
That's weird, it worked for me like I posted it in my end. Maybe different matplotlib versions?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.