如何将 pandas 日期时间Xticks转换为可读格式? [英] How can I convert pandas date time xticks to readable format?

查看:89
本文介绍了如何将 pandas 日期时间Xticks转换为可读格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在绘制带有日期时间索引的时间序列.该图必须是日记格式的特定大小.因此,这些棍子跨越了很多年,因此无法读取.

I am plotting a time series with a date time index. The plot needs to be a particular size for the journal format. Consequently, the sticks are not readable since they span many years.

这是一个数据样本

2013-02-10  0.7714492098202259
2013-02-11  0.7709101833765016
2013-02-12  0.7704911332770049
2013-02-13  0.7694975914173087
2013-02-14  0.7692108921323576

数据是一个具有日期时间索引的系列,范围从2013年到2016年.我使用

The data is a series with a datetime index and spans from 2013 to 2016. I use

data.plot(ax = ax)

绘制数据.

如何格式化我的xticks以使其像'13而不是2013?

How can I format my xticks to read like '13 instead of 2013?

推荐答案

在日期方面,熊猫和matplotlib格式化程序/定位器之间似乎有些不兼容.参见例如这些问题:

It seems there is some incompatibility between pandas and matplotlib formatters/locators when it comes to dates. See e.g. those questions:

在xaxis上的熊猫数据框线图显示日期

我不完全确定为什么在某些情况下使用matplotlib格式化程序仍然可以工作,而在其他情况下却无法使用.但是,由于这些问题,防弹解决方案是使用matplotlib绘制图形而不是pandas绘制函数. 就像 matplotlib示例一样.

I'm not entirely sure why it still works in some cases to use matplotlib formatters and not in others. However because of those issues, the bullet-proof solution is to use matplotlib to plot the graph instead of the pandas plotting function. This allows to use locators and formatters just as seen in the matplotlib example.

此问题的解决方案如下:

Here the solution to the question would look as follows:

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

dates = pd.date_range("2013-01-01", "2017-06-20" )
y = np.cumsum(np.random.normal(size=len(dates)))

s = pd.Series(y, index=dates)

fig, ax = plt.subplots()
ax.plot(s.index, s.values)

ax.xaxis.set_major_locator(mdates.YearLocator())
ax.xaxis.set_minor_locator(mdates.MonthLocator())
yearFmt = mdates.DateFormatter("'%y")
ax.xaxis.set_major_formatter(yearFmt)

plt.show()

这篇关于如何将 pandas 日期时间Xticks转换为可读格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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