gpt4 book ai didi

python - 根据特定日期设置 matplotlib 网格刻度

转载 作者:行者123 更新时间:2023-12-02 04:14:57 26 4
gpt4 key购买 nike

我正在绘制 Pandas 系列 30 年的日期时间。 x 轴是日期:

Datetime
1965-06-08 3545
1965-06-09 6378
1965-06-10 9857
1965-06-11 2528
....
Freq: W-SUN, dtype: int64

我希望每个月都有一个“小滴答”,每年都有一个“大滴答”。

因为这是三十年的数据,手动放置刻度是行不通的。

基于 matplotlib 的日期 API,http://matplotlib.org/api/dates_api.html

是否可以在每个月设置一个刻度?

如果我要手动设置网格,我会这样做:

import numpy as np                                                               
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1,1,1)

# This is where I manually set ticks. Can I use Datetime data instead???
major_ticks = np.arange(0, 101, 20)
minor_ticks = np.arange(0, 101, 5)

ax.set_xticks(major_ticks)
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(major_ticks)
ax.set_yticks(minor_ticks, minor=True)
ax.grid(which='both')
ax.grid(which='minor', alpha=0.3)
ax.grid(which='major', alpha=0.4)
plt.show()

enter image description here

最佳答案

你想要matplotlib.dates.YearLocatormatplotlib.dates.MonthLocator :

import matplotlib.pyplot as plt
from matplotlib.dates import MonthLocator, YearLocator
import numpy as np

fig, ax = plt.subplots(1, 1)

x = np.arange('1965-01', '1975-07', dtype='datetime64[D]')
y = np.random.randn(x.size).cumsum()
ax.plot(x, y)

yloc = YearLocator()
mloc = MonthLocator()
ax.xaxis.set_major_locator(yloc)
ax.xaxis.set_minor_locator(mloc)
ax.grid(True)

enter image description here

关于python - 根据特定日期设置 matplotlib 网格刻度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34387349/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com