Python 在 matplotlib 中编辑 x 轴刻度标签的日期格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14946371/
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-08-18 12:55:34  来源:igfitidea点击:

Editing the date formatting of x-axis tick labels in matplotlib

pythonmatplotlib

提问by Osmond Bishop

I am looking to edit the formatting of the dates on the x-axis. The picture below shows how they appear on my bar graph by default. I would like to remove the repetition of 'Dec' and '2012' and just have the actual date numbers along the x-axis.

我希望编辑 x 轴上日期的格式。下图显示了默认情况下它们在我的条形图上的显示方式。我想删除 'Dec' 和 '2012' 的重复,只在 x 轴上有实际的日期数字。

Any suggestions as to how I can do this?

关于我如何做到这一点的任何建议?

enter image description here

在此处输入图片说明

采纳答案by Paul H

In short:

简而言之:

import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)

Many examples on the matplotlib website. The one I most commonly use is here

matplotlib 网站上的许多示例。我最常用的一个是这里

回答by Robino

While the answer given by Paul H shows the essential part, it is not a complete example. On the other hand the matplotlib exampleseems rather complicated and does not show how to use days.

虽然 Paul H 给出的答案显示了基本部分,但它不是一个完整的例子。另一方面,matplotlib 示例似乎相当复杂,并且没有显示如何使用 days。

So for everyone in need here is a full working example:

因此,对于有需要的每个人,这里是一个完整的工作示例:

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

myDates = [datetime(2012,1,i+3) for i in range(10)]
myValues = [5,6,4,3,7,8,1,2,5,4]
fig, ax = plt.subplots()
ax.plot(myDates,myValues)

myFmt = DateFormatter("%d")
ax.xaxis.set_major_formatter(myFmt)

## Rotate date labels automatically
fig.autofmt_xdate()
plt.show()