英文:
Matplotlib major and minor ticks misaligned when using pandas date_range
问题
我正在尝试在 matplotlib.pyplot 图表的 x 轴上使用 pandas 的 date_range
,同时将年份设置为主要刻度,月份设置为次要刻度(用于时间轴图)。
我遇到了一个看似意外的行为(也注意到作为此SO问题的一部分,但没有解决),其中刻度没有对齐,并且存在偏移。
这段代码为我重现了这个问题(v3.5.2):
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import matplotlib.dates as mdates
x_range = pd.date_range('2015-01-01', '2021-06-01', freq='m')
y = np.linspace(1, 1, len(x_range))
fig, ax = plt.subplots(figsize=(10, 1))
ax.plot(x_range, y)
loc = mdates.MonthLocator(interval=12)
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_minor_locator(AutoMinorLocator(12))
fmt = mdates.DateFormatter('%Y')
ax.xaxis.set_major_formatter(fmt)
有人之前遇到过这个问题吗?我怀疑这与月份的天数不同有关,但无法进一步调查。
英文:
I am trying to use pandas date_range
in the x-axis of a matplotlib.pyplot graph, while setting years to be the major ticks and months to be the minor ticks (for a timeline plot).
I came across a seemingly unexpected behaviour (noticed also as part of this SO question but unsolved), where the ticks are not aligned, and they are exhibiting an offset.
This code reproduces it for me (v3.5.2):
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import matplotlib.dates as mdates
x_range = pd.date_range('2015-01-01', '2021-06-01', freq='m')
y = np.linspace(1,1, len(x_range))
fig, ax = plt.subplots(figsize=(10, 1))
ax.plot(x_range, y)
loc = mdates.MonthLocator(interval=12)
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_minor_locator(AutoMinorLocator(12))
fmt = mdates.DateFormatter('%Y')
ax.xaxis.set_major_formatter(fmt)
Anyone dealt with this before? I suspect it has to do with months having 28, 30 and 31 days but could not investigate further.
答案1
得分: 1
以下是代码的翻译部分:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import matplotlib.dates as mdates
x_range = pd.date_range('2015-01-01', '2021-06-01', freq='A')
y = np.linspace(1, 1, len(x_range))
fig, ax = plt.subplots(figsize=(10, 1))
ax.plot(x_range, y)
loc = mdates.YearLocator()
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_minor_locator(mdates.MonthLocator())
fmt = mdates.DateFormatter('%Y')
ax.xaxis.set_major_formatter(fmt)
plt.show()
英文:
You could do the following:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import matplotlib.dates as mdates
x_range = pd.date_range('2015-01-01', '2021-06-01', freq='A')
y = np.linspace(1, 1, len(x_range))
fig, ax = plt.subplots(figsize=(10, 1))
ax.plot(x_range, y)
loc = mdates.YearLocator()
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_minor_locator(mdates.MonthLocator())
fmt = mdates.DateFormatter('%Y')
ax.xaxis.set_major_formatter(fmt)
plt.show()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论