使用 matplotlib 绘制时间序列数据并仅在年初显示年份 [英] Plotting time-series data using matplotlib and showing year only at start of year

查看:124
本文介绍了使用 matplotlib 绘制时间序列数据并仅在年初显示年份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

rcParams['date.autoformatter.month'] = "%b\n%Y"

我正在使用 matpltolib 绘制时间序列,如果我按上述方式设置 rcParams,则生成的图会在每个刻度处标记月份名称和年份.我如何设置它以便仅在每年的 1 月绘制该年份.我尝试这样做,但是不起作用:

I am using matpltolib to plot a time-series and if I set rcParams as above, the resulting plot has month name and year labeled at each tick. How can I set it up so that year is only plotted at january of each year. I tried doing this, but it does not work:

rcParams['date.autoformatter.month'] = "%b"
rcParams['date.autoformatter.year'] = "%Y"

推荐答案

格式化程序不允许对它们指定条件.根据系列的跨度,AutoDateFormatter 将落入 date.autoformatter.month 范围或 date.autoformatter.year 范围.

The formatters do not allow to specify conditions on them. Depending on the span of the series, the AutoDateFormatter will either fall into the date.autoformatter.month range or the date.autoformatter.year range.

此外,AutoDateLocator 可能根本就不一定决定实际勾选一月一日.

Also, the AutoDateLocator may not necessarily decide to actually tick the first of January at all.

因此,我建议直接将代码指定为所需的格式和位置.您可以使用大刻度线显示年份,使用小刻度线显示月份.然后,主要刻度线的格式可以换行,以免与次要刻度线标签重叠.

I would hence suggest to specify the tickers directly to the desired format and locations. You may use the major ticks to show the years and the minor ticks to show the months. The format for the major ticks can then get a line break, in order not to overlap with the minor ticklabels.

import matplotlib.pyplot as plt
import matplotlib.dates
from datetime import datetime

t = [datetime(2016,1,1), datetime(2017,12,31)]
x = [0,1]

fig, ax = plt.subplots()
ax.plot(t,x)

ax.xaxis.set_major_locator(matplotlib.dates.YearLocator())
ax.xaxis.set_minor_locator(matplotlib.dates.MonthLocator((1,4,7,10)))

ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("\n%Y"))
ax.xaxis.set_minor_formatter(matplotlib.dates.DateFormatter("%b"))
plt.setp(ax.get_xticklabels(), rotation=0, ha="center")

plt.show()

然后,您还可以根据需要调整次要壁虱的长度,使其与主要壁虱的长度相匹配,

You could then also adapt the minor ticks' lengths to match those of the major ones in case that is desired,

ax.tick_params(axis="x", which="both", length=4)

这篇关于使用 matplotlib 绘制时间序列数据并仅在年初显示年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆