【问题标题】:Python matplotlib subplot datetime x ticks cutomizationPython matplotlib subplot datetime xticks 自定义
【发布时间】: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


【解决方案1】:

简单的方法是使用text添加文本,但它不是自动的,需要一些调整。或者你可以得到axe的tightbbox,根据bbox添加文字。这里我放了最简单的方法:添加相对于轴的文本。

import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np

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))

lims = [(np.datetime64('2005-02'), np.datetime64('2005-04')),
        (np.datetime64('2005-02-03'), np.datetime64('2005-02-15')),
        (np.datetime64('2005-02-03 11:00'), np.datetime64('2005-02-04 13:20'))]

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')
axs[0].text(0, -0.28, 'Feb 2005', transform=axs[0].transAxes)
axs[1].text(0, -0.28, 'Feb 2005', transform=axs[1].transAxes)
axs[2].text(0, -0.28, '04 Feb 2005', transform=axs[2].transAxes)

【讨论】:

    猜你喜欢
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 2023-01-09
    • 1970-01-01
    • 2021-07-10
    相关资源
    最近更新 更多