如何使用月/年分辨率(只需几行代码)来绘制 pandas 时间序列? [英] How to plot a pandas timeseries using months/year resolution (with few lines of code)?

查看:79
本文介绍了如何使用月/年分辨率(只需几行代码)来绘制 pandas 时间序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们要绘制一个时间序列,例如:

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

结果是一个图,其中x轴以年为标签,我想获取月-年标签.有没有一种快速的方法(可以避免使用数十行调用matplotlib的复杂代码)?

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

推荐答案

Pandas对Axes对象做了一些非常奇怪的事情,很难避免matplotlib调用.

Pandas does some really weird stuff to the Axes objects, making it hard to avoid matplotlib calls.

这就是我要怎么做

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

这给了我:

这篇关于如何使用月/年分辨率(只需几行代码)来绘制 pandas 时间序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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