【发布时间】:2021-01-20 16:02:16
【问题描述】:
https://matplotlib.org/3.1.0/gallery/ticks_and_spines/date_concise_formatter.html 提供了自定义 x 轴日期的解决方案。我想进一步定制它。解决办法是
import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
base = datetime.datetime(2005, 2, 1)
dates = np.array([base + datetime.timedelta(hours=(2 * i))
for i in range(732)])
N = len(dates)
np.random.seed(19680801)
y = np.cumsum(np.random.randn(N))
fig, axs = plt.subplots(3, 1, constrained_layout=True, figsize=(6, 6))
for nn, ax in enumerate(axs):
locator = mdates.AutoDateLocator()
formatter = mdates.ConciseDateFormatter(locator)
formatter.formats = ['%y', # ticks are mostly years
'%b', # ticks are mostly months
'%d', # ticks are mostly days
'%H:%M', # hrs
'%H:%M', # min
'%S.%f', ] # secs
# these are mostly just the level above...
formatter.zero_formats = [''] + formatter.formats[:-1]
# ...except for ticks that are mostly hours, then it is nice to have
# month-day:
formatter.zero_formats[3] = '%d-%b'
formatter.offset_formats = ['',
'%Y',
'%b %Y',
'%d %b %Y',
'%d %b %Y',
'%d %b %Y %H:%M', ]
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
ax.plot(dates, y)
ax.set_xlim(lims[nn])
axs[0].set_title('Concise Date Formatter')
plt.show()
目前的输出:
上面的代码在 x 轴的末尾添加了数据的年份。我也想在 a 轴的开头添加数据的年份。在第一个子图 x 轴中,2015 出现在 x 轴的末端。如何让它也出现在 x 轴的开头?
【问题讨论】:
-
你不能轻易做到;我相信,额外的日期信息位于轴的“偏移量”中,并且位于轴上的固定位置。但是,您可以获取第一个刻度的文本,并在文本中添加回车并添加年份。
-
@JodyKlymak 不熟悉子图,我还没有完全理解。但你似乎知道那里发生了什么。你能帮我看看我应该如何处理它吗?
-
@JodyKlymak 感谢您对我的新问题提出的意见stackoverflow.com/questions/64225835/…
标签: python datetime matplotlib subplot