更改 matplotlib 中日期时间轴的格式 [英] Changing the formatting of a datetime axis in matplotlib
本文介绍了更改 matplotlib 中日期时间轴的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个索引为 datetime
的系列,我希望绘制它.我想在 y 轴上绘制系列的值,在 x 轴上绘制系列的索引.系列
如下所示:
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:
问题是我只想有年和月(yyyy-mm 或 2016 年 3 月).但是,该图表包含小时、分钟和秒.如何删除它们以便获得所需的格式?
The problem is that I would like to have only year and month (yyyy-mm or 2016 March). However, the graph contains hours, minutes and seconds. How can I remove them so that I get my desired formatting?
推荐答案
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# sample data
N = 30
drange = pd.date_range("2014-01", periods=N, freq="MS")
np.random.seed(365) # for a reproducible example of values
values = {'values':np.random.randint(1,20,size=N)}
df = pd.DataFrame(values, index=drange)
fig, ax = plt.subplots()
ax.plot(df.index, df.values)
ax.set_xticks(df.index)
# use formatters to specify major and minor ticks
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))
ax.xaxis.set_minor_formatter(mdates.DateFormatter("%Y-%m"))
_ = plt.xticks(rotation=90)
这篇关于更改 matplotlib 中日期时间轴的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文