使用 matplotlib 绘制绘图时 X 轴刻度标签太密集 [英] X-axis tick labels are too dense when drawing plots with matplotlib

查看:82
本文介绍了使用 matplotlib 绘制绘图时 X 轴刻度标签太密集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在绘制matplotlib图,我的x轴由YYYYMM格式的年和月字符串组成,如 201901 于2019年1月.

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

我的问题是某些数据跨度很长,这使x轴刻度标签变得如此密集,以致于它们彼此堆积在一起,变得不可读.

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.

我尝试将字体变小并将标签旋转 90 度,这有很大帮助,但对于我的某些数据来说仍然不够.

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.

这是我的一个 x 轴的示例,它看起来不错:

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

这里是一个 x 轴的例子,它太密集了,因为数据跨越了很长一段时间:

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

所以我希望 matplotlib 在刻度标签开始相互堆积时跳过打印几个刻度标签.例如,打印一月的标签,跳过打印二月,三月,四月和五月的标签,打印六月的标签,跳过打印七月,八月的标签,等等.但是我不知道该怎么做?

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?

推荐答案

一种快速的肮脏解决方案如下:

A quick dirty solution would be the following:

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

这只会显示每秒的 xtick.如果您只想显示第n个刻度,则可以使用

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])

如果你没有ax的句柄,你可以得到一个ax = plt.gca().

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

或者,您可以指定要用于的xticks数量:

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

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

这篇关于使用 matplotlib 绘制绘图时 X 轴刻度标签太密集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆