I've created following graph with pd.Series([1]*month_limits.size, month_limits).plot(ax=ax)
How do I recreate same x ticks labels with just matplotlib? I mean years and month not overriding each other enter image description here

我得到的最好的是同时拥有几年和几个月,但几年压倒了几个月

import datetime

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd

month_limits = pd.date_range('2021-08', '2023-01', freq="1m",
                             normalize=True) + datetime.timedelta(days=1)
plt.plot(month_limits, [1]*month_limits.size)

l1 = mdates.YearLocator()
l2 = mdates.MonthLocator(interval=1)
ax.xaxis.set_major_locator(l1)
ax.xaxis.set_minor_locator(l2)
ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(l1))
ax.xaxis.set_minor_formatter(mdates.ConciseDateFormatter(l2))

enter image description here

推荐答案

  • 使用set_minor_locatorset_minor_formatter表示月份'%b'
  • Use set_major_locator and set_major_formatter for the month and year '%b\n%Y'
    • mdates.YearLocator(month=1),其中month是显示年份的月份.
  • 一百零二
month_limits = pd.date_range('2021-08', '2023-01', freq="1m", normalize=True) +  pd.Timedelta(days=1)

fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(month_limits, [1]*month_limits.size)

# set locators
ax.xaxis.set_minor_locator(mdates.MonthLocator(interval=2))
ax.xaxis.set_major_locator(mdates.YearLocator(month=1))
# set formatters
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b\n%Y'))
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%b'))

enter image description here

month_limits = pd.date_range('2021-08', '2023-01', freq="1m", normalize=True) + pd.Timedelta(days=1)

fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(month_limits, [1]*month_limits.size)

# set locators
ax.xaxis.set_minor_locator(mdates.MonthLocator(bymonth=range(1, 13, 3)))
ax.xaxis.set_major_locator(mdates.YearLocator(month=1))
# set formatter
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b\n%Y'))
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%b'))

enter image description here

Python相关问答推荐

Tkinter滑动条标签.我不确定如何删除滑动块标签或更改其文本

即使在可见的情况下也不相互作用

重新匹配{ }中包含的文本,其中文本可能包含{{var}

ModuleNotFound错误:没有名为Crypto Windows 11、Python 3.11.6的模块

如何找到满足各组口罩条件的第一行?

在线条上绘制表面

在Wayland上使用setCellWidget时,try 编辑QTable Widget中的单元格时,PyQt 6崩溃

numpy卷积与有效

如何在Raspberry Pi上检测USB并使用Python访问它?

Pandas计数符合某些条件的特定列的数量

启用/禁用shiny 的自动重新加载

如何禁用FastAPI应用程序的Swagger UI autodoc中的application/json?

ConversationalRetrivalChain引发键错误

通过追加列表以极向聚合

处理Gekko的非最优解

如何在Airflow执行日期中保留日期并将时间转换为00:00

如何在信号的FFT中获得正确的频率幅值

如何训练每一个pandaprame行的线性回归并生成斜率

在round函数中使用列值

以极轴表示的行数表达式?