Matplotlib-X轴与日期时间之间的间隔不均匀 [英] Matplotlib - uneven intervals between x-axis with datetime

查看:446
本文介绍了Matplotlib-X轴与日期时间之间的间隔不均匀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前遇到一个问题,当在我的x轴上使用DatetimeIndex时,图上刻度线之间的间隔似乎具有不均匀的间隔.代码如下:

I am currently experiencing an issue where the spaces between ticks on my plot appear to have uneven intervals when using a DatetimeIndex for my x-axis. The code is as follows:

x = pd.date_range('2018-11-03', '2018-12-30')
plt.plot(x, np.arange(len(x)))
plt.xticks(rotation=45)

请注意两个实例中的日期通常不增加7天的时间.即使延长了时间,问题仍然存在:

Note the two instances in which the dates do not increment by the typical 7-day period. Even after extending the time period, the issue persists:

x = pd.date_range('2018-11-03', '2019-03-20')
plt.plot(x, np.arange(len(x)))
plt.xticks(rotation=45)

我如何覆盖此行为,以在地块上使用标准的7天间隔?谢谢.

How can I override this behavior to have standard 7-day intervals on my plot? Thank you.

推荐答案

您可以使用matplotlib的代码模块自定义标记位置:

You can use matplotlib's ticker module to customize tick locations:

import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.ticker as ticker

x = pd.date_range('2018-11-03', '2019-03-20')
plt.plot(x, np.arange(len(x)))
plt.xticks(rotation=45)
ax=plt.gca()
ax.xaxis.set_major_locator(ticker.MultipleLocator(7))

上面的脚本返回以下图像:

The above script returns the following image:

这篇关于Matplotlib-X轴与日期时间之间的间隔不均匀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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