问题描述
我当前遇到一个问题,当在我的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轴与日期时间之间的间隔不均匀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!