Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

python - X-axis tick labels are too dense when drawing plots with matplotlib

I am drawing matplotlib plots and my x axis consists of YYYYMM formatted strings of year and month like 201901 for January of 2019.

My problem is that some of the data spans on a long period of time and this makes the x axis tick labels so dense that they pile up on each other and they become unreadable.

I tried making the font smaller and I rotated the labels 90 degrees which helped a lot but it is still not enough for some of my data.

Here is an example of one of my x axis which looks ok:

x-axis that looks fine

And here is an example of an x axis which is too dense because the data spans on a long period of time:

x-axis labels that are too dense

So I want matplotlib to skip printing a few tick labels when the tick labels start piling up on each other. For example, print the label for January, skip printing the labels for February, March, April and May, print the label for June, and skip printing the labels for July, August etc. But I don't know how to do this?

Or are there any other kind of solutions I can use to overcome this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A quick dirty solution would be the following:

ax.set_xticks(ax.get_xticks()[::2])

This would only display every second xtick. If you wanted to only display every n-th tick you would use

ax.set_xticks(ax.get_xticks()[::n])

If you don't have a handle on ax you can get one as ax = plt.gca().

Alternatively, you could specify the number of xticks to use with:

plt.locator_params(axis='x', nbins=10)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...