clicky
clicky

Reputation: 865

Pyplot spacing of tick labels on x axis

What is the correct approach to spacing out xticks in a pyplot chart? For example I am trying to plot logarithms in a Jupiter notebook. I have a lot of data points on the y axis and this creates too many xticks (the labels overlap each other and are unreadable). How do I configure the plot to only print a label every 10 xticks?

I tried to use

plt.xticks(np.arange(10))

but this just renders the first 10 labels in the same tightly grouped fashion.

%matplotlib inline
import matplotlib.pyplot as plt
x = np.arange(0.1, 10, 0.1)
plt.plot(np.log(x), label='$\log_e$')
plt.plot(np.log2(x), label='$\log_2$')
plt.plot(np.log10(x), label='$\log_{10}$')
plt.xticks(np.arange(10))
plt.grid()
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

bad xticks

Upvotes: 1

Views: 7250

Answers (2)

LuckyJosh
LuckyJosh

Reputation: 146

A part of your problem arises, because you have omitted the x coordinates in your plot functions. If you were using

plt.plot(x, np.log(x))

you would not have the spacing problem.

If you omit the x coordinate it gets replaced internaly by a np.arange(len(y)) and so your xaxis has values from 0 to 100 instead of 0 to 10.

For reference:

enter image description here enter image description here

In general matplotlib has socalled locators to deal with tick spacings:
https://matplotlib.org/examples/ticks_and_spines/tick-locators.html

Upvotes: 2

Steve Barnes
Steve Barnes

Reputation: 28370

One option is to use log axees e.g. change:

plt.xticks(np.arange(10))

to:

plt.semilogx(np.arange(10))

And you will get: enter image description here

See https://matplotlib.org/api/_as_gen/matplotlib.pyplot.semilogx.html?highlight=semilogx#matplotlib.pyplot.semilogx for more options.

One option is to give a list of values to the ticks:

plt.xticks([0,10,30,100])

Will give: enter image description here

but there are other options such as specifying a step to the arange function.

Upvotes: 2

Related Questions