在 matplotlib 中格式化日期时间 xlabels(pandas df.plot() 方法)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23088241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:55:47  来源:igfitidea点击:

Formatting datetime xlabels in matplotlib (pandas df.plot() method)

pythonmatplotlibpandas

提问by Dan

I can't figure out how to change the format of these x-labels. Ideally, I'd like to call strftime('%Y-%m-%d')on them. I've tried things like set_major_formatterbut was unsuccessful.

我不知道如何更改这些 x 标签的格式。理想情况下,我想拜访strftime('%Y-%m-%d')他们。我尝试过类似的事情,set_major_formatter但没有成功。

import pandas as pd
import numpy as np
date_range = pd.date_range('2014-01-01', '2015-01-01', freq='MS')
df = pd.DataFrame({'foo': np.random.randint(0, 10, len(date_range))}, index=date_range)
ax = df.plot(kind='bar')

ugly x label formats

丑陋的 x 标签格式

采纳答案by wflynny

The objects in the date_rangeDF are Timestampobjects. Call Timestamp.strftimeon each object:

在对象date_rangeDF的Timestamp对象。调用Timestamp.strftime每个对象:

date_range = pd.date_range('2014-01-01', '2015-01-01', freq='MS')
date_range = date_range.map(lambda t: t.strftime('%Y-%m-%d'))
print date_range
array([2014-01-01, 2014-02-01, 2014-03-01, 2014-04-01, 2014-05-01,
       2014-06-01, 2014-07-01, 2014-08-01, 2014-09-01, 2014-10-01,
       2014-11-01, 2014-12-01, 2015-01-01], dtype=object)

This allows for more general formatting options versus truncating the ticklabel string.

与截断刻度标签字符串相比,这允许使用更通用的格式选项。

回答by CT Zhu

Simply access the tick labels and change them:

只需访问刻度标签并更改它们:

xtl=[item.get_text()[:10] for item in ax.get_xticklabels()]
_=ax.set_xticklabels(xtl)

enter image description here

在此处输入图片说明

回答by RCCG

You could just pass new labels exactly with your preferred strftime:

您可以完全使用您喜欢的 strftime 传递新标签:

ax.set_xticklabels([pandas_datetime.strftime("%Y-%m-%d") for pandas_datetime in df.index])

It's not the prettiest answer, but it gets the job done consistently.

这不是最漂亮的答案,但它始终如一地完成工作。