#python #datetime #matplotlib
Вопрос:
Использование mdates.ConciseDateFormatter
в нескольких подзаголовках приводит к ошибочному смещению оси:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
dti = pd.to_datetime(["2016-08-31", "2016-09-30"])
ts0 = pd.DataFrame({"x": [0, 1]}, index=dti)
ts1 = pd.DataFrame({"x": [0, 1]}, index=dti pd.Timedelta(365, "D"))
fig, axs = plt.subplots(2, 1, sharex=False)
ts0["x"].plot(ax=axs[0], marker="o")
ts1["x"].plot(ax=axs[1], marker="o")
dlocator = mdates.AutoDateLocator(minticks=6, maxticks=9)
axs[0].xaxis.set_major_locator(dlocator)
axs[0].xaxis.set_major_formatter(mdates.ConciseDateFormatter(dlocator))
axs[1].xaxis.set_major_locator(dlocator)
axs[1].xaxis.set_major_formatter(mdates.ConciseDateFormatter(dlocator))
На рисунке показаны метки галочек по оси x для верхнего участка, которые были перепутаны при назначении основного локатора и форматирования нижнему участку. Есть ли какое-либо решение этой ошибки или проблемы?
Ответ №1:
- Требуется создать экземпляр
AutoDateLocator
для каждогоaxes
- См. Раздел Форматирование галочек даты с помощью
ConciseDateFormatter
- По мере форматирования оси графика
locator
объект изменяется, поэтому он не может быть повторно использован для последующегоaxes
.
- См. Раздел Форматирование галочек даты с помощью
matplotlib.dates.ConciseDateFormatter
matplotlib.dates.AutoDateLocator
- Протестировано в
python 3.8.11
,pandas 1.3.3
,matplotlib 3.4.3
Код настройки графика
fig, axs = plt.subplots(2, 1, sharex=False, figsize=(7, 7))
# axs = axs.flatten() # required to easily index subplots, if subplots >= 2x2
ts0["x"].plot(ax=axs[0], marker="o")
ts1["x"].plot(ax=axs[1], marker="o")
Вариант 1
# instantiate AutoDateLocator
locator = mdates.AutoDateLocator(minticks=6, maxticks=9)
axs[0].xaxis.set_major_locator(locator)
axs[0].xaxis.set_major_formatter(mdates.ConciseDateFormatter(locator))
# instantiate AutoDateLocator
locator = mdates.AutoDateLocator(minticks=6, maxticks=9)
axs[1].xaxis.set_major_locator(locator)
axs[1].xaxis.set_major_formatter(mdates.ConciseDateFormatter(locator))
fig.tight_layout()
Вариант 2
for ax in axs:
# instantiate AutoDateLocator
locator = mdates.AutoDateLocator(minticks=6, maxticks=9)
formatter = mdates.ConciseDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
fig.tight_layout()