Python 更改 matplotlib 中日期时间轴的格式

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

Changing the formatting of a datetime axis in matplotlib

pythonpandasdatetimematplotlibpython-datetime

提问by Sheryl

I have a series whose index is datetimethat I wish to plot. I want to plot the values of the series on the y axis and the index of the series on the x axis. The Serieslooks as follows:

我有一个系列,其索引是datetime我希望绘制的。我想在 y 轴上绘制系列的值,在 x 轴上绘制系列的索引。该Series如下外观:

2014-01-01     7
2014-02-01     8
2014-03-01     9
2014-04-01     8
...

I generate a graph using plt.plot(series.index, series.values). But the graph looks like:

我使用plt.plot(series.index, series.values). 但图形看起来像:

graph

图形

The problem is that I would like to have only year and month. However, the graph contains hours, minutes and seconds. How can I remove them so that I get my desired formatting?

问题是我只想有年和月。但是,图表包含小时、分钟和秒。如何删除它们以便获得所需的格式?

回答by andrew_reece

# sample data
import numpy as np
import pandas as pd

N = 30
drange = pd.date_range("2014-01", periods=N, freq="MS")
values = {'values':np.random.randint(1,20,size=N)}
df = pd.DataFrame(values, index=drange)

# use formatters to specify major and minor ticks
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

fig, ax = plt.subplots()
ax.plot(df.index, df.values)
ax.set_xticks(df.index)
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))
ax.xaxis.set_minor_formatter(mdates.DateFormatter("%Y-%m"))
_=plt.xticks(rotation=90)    

time series plot

时间序列图

回答by Scott Boston

You can try something like this:

你可以尝试这样的事情:

import matplotlib.dates as mdates
import matplotlib.pyplot as plt
df = pd.DataFrame({'values':np.random.randint(0,1000,36)},index=pd.date_range(start='2014-01-01',end='2016-12-31',freq='M'))
fig,ax1 = plt.subplots()
plt.plot(df.index,df.values)
monthyearFmt = mdates.DateFormatter('%Y %B')
ax1.xaxis.set_major_formatter(monthyearFmt)
_ = plt.xticks(rotation=90)

enter image description here

在此处输入图片说明