pandas 如何使用月/年分辨率(用几行代码)绘制熊猫时间序列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24620712/
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
How to plot a pandas timeseries using months/year resolution (with few lines of code)?
提问by Mannaggia
Assume we want to plot a time series, e.g.:
假设我们要绘制时间序列,例如:
import pandas as pd
import numpy as np
a=pd.DatetimeIndex(start='2010-01-01',end='2014-01-01' , freq='D')
b=pd.Series(np.randn(len(a)), index=a)
b.plot()
The result is a figure in which the x-axis has years as labels, I would like to get month-year labels. Is there a fast way to do this (possibly avoiding the use of tens of lines of complex code calling matplotlib)?
结果是一个数字,其中 x 轴有年份作为标签,我想获得月-年标签。有没有快速的方法来做到这一点(可能避免使用几十行复杂的代码调用 matplotlib)?
回答by Paul H
Pandas does some really weird stuff to the Axesobjects, making it hard to avoid matplotlib calls.
Pandas 对Axes对象做了一些非常奇怪的事情,使得很难避免 matplotlib 调用。
Here's how I would do it
这是我将如何做到的
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
a = pd.DatetimeIndex(start='2010-01-01',end='2014-01-01' , freq='D')
b = pd.Series(np.random.randn(len(a)), index=a)
fig, ax = plt.subplots()
ax.plot(b.index, b)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
which give me:

这给了我:


