Python 更改matplotlib中日期时间轴的格式
我有一个系列,它的索引是Python 更改matplotlib中日期时间轴的格式,python,pandas,datetime,matplotlib,python-datetime,Python,Pandas,Datetime,Matplotlib,Python Datetime,我有一个系列,它的索引是datetime,我希望绘制它。我想在y轴上绘制系列的值,在x轴上绘制系列的索引。系列如下所示: 2014-01-01 7 2014-02-01 8 2014-03-01 9 2014-04-01 8 ... 我使用plt.plot(series.index,series.values)生成一个图形。但图表如下所示: 问题是我只希望有一年和一个月。但是,图表包含小时、分钟和秒。如何删除它们以获得所需的格式?您可以尝试以下方法: impo
datetime
,我希望绘制它。我想在y轴上绘制系列的值,在x轴上绘制系列的索引。系列
如下所示:
2014-01-01 7
2014-02-01 8
2014-03-01 9
2014-04-01 8
...
我使用plt.plot(series.index,series.values)
生成一个图形。但图表如下所示:
问题是我只希望有一年和一个月。但是,图表包含小时、分钟和秒。如何删除它们以获得所需的格式?您可以尝试以下方法:
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)
您是否也可以共享生成此图表的代码?这将为您提供更好的解决方案。谢谢@ScottBoston,我添加了绘图命令。您想要天吗?谢谢@pshep123否,我只想要yyyy-mm格式的年和月。如果熊猫也能将其转换为2016年3月,那就更好了。我需要删除ax.set_xticks(df.index)这一行才能工作。
# 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)