在matplotlib中更改日期时间轴的格式 [英] Changing the formatting of a datetime axis in matplotlib

查看:193
本文介绍了在matplotlib中更改日期时间轴的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要绘制的索引为datetime的系列.我想在y轴上绘制系列的值,并在x轴上绘制系列的索引. Series看起来如下:

I have a series whose index is datetime that 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 Series looks as follows:

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

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

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

问题是我只希望有年份和月份.但是,该图包含小时,分钟和秒.如何删除它们,以便获得所需的格式?

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?

推荐答案

# 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)    

这篇关于在matplotlib中更改日期时间轴的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆