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
Editing the date formatting of x-axis tick labels in matplotlib
提问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?
关于我如何做到这一点的任何建议?


采纳答案by Paul H
回答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()

