从带有timedelta索引的 pandas 数据帧进行绘图 [英] Plotting from a pandas dataframe with a timedelta index

查看:74
本文介绍了从带有timedelta索引的 pandas 数据帧进行绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从带有timedelta索引的pandas数据框中绘制一些数据,我想在x轴上自定义时间刻度和标签.这应该很简单,但事实证明这是一项艰巨的任务.

I'm trying to plot some data from a pandas dataframe with a timedelta index and I want to customize the time ticks and labels in my x-axis. This should be simple but it's proving to be a tough job.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as dates

## I have a df similar to this
timestamps = pd.date_range(start="2017-05-08", freq="10T", periods=6*6)
timedeltas = timestamps - pd.to_datetime("2017-05-08")
yy = np.random.random((len(timedeltas),10))
df = pd.DataFrame(data=yy, index=timedeltas)  # Ok, this is what I have

## Now I want to plot this but I want detailed control of the plot so I use matplotlib instead of df.plot
fig,axes=plt.subplots()
axes.plot(df.index.values, df.values)
#axes.plot_date(df.index, df.values, '-')

axes.xaxis.set_major_locator(dates.HourLocator(byhour=range(0,24,2)))
axes.xaxis.set_minor_locator(dates.MinuteLocator(byminute=range(0,24*60,10)))
axes.xaxis.set_major_formatter(dates.DateFormatter('%H:%M'))

plt.show()

如您所见,刻度线甚至没有显示出来.例如,如何每两个小时添加一次大刻度线和标签,并每隔10分钟添加一次小刻度线?

As you can see, the ticks are not even showing up. How can I add major ticks and labels every two hours and minor ticks every 10 minutes, for example?

推荐答案

尽管我不确定确切的根本问题是什么,但似乎与所使用的软件包版本有关.当我使用较旧的python发行版(matplotlib 1.5.1,numpy 1.11.1,pandas 0.18.1和python 2.7.12)运行您的示例时,我得到的图没有您所描述的滴答声.

Although I don't know exactly what the root issue is, it seems that it is related to the used package versions. When I run your example with an older python distribution (matplotlib 1.5.1, numpy 1.11.1, pandas 0.18.1 and python 2.7.12), then I get a plot without ticks just as you described.

但是我可以得到带有正确刻度的图

However I can get a plot with the correct ticks

通过使用最新的python发行版(matplot 2.0.1,numpy 1.12.1,pandas 0.19.1和python 3.6.1)运行以下代码.

by running the code below with a recent python distribution (matplot 2.0.1, numpy 1.12.1, pandas 0.19.1 and python 3.6.1).

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as dates

timestamps = pd.date_range(start="2017-05-08", freq="10T", periods=6*6)
timedeltas = timestamps - pd.to_datetime("2017-05-08")
yy = np.random.random((len(timedeltas),10))
df = pd.DataFrame(data=yy, index=timedeltas)

fig,axes=plt.subplots()
axes.plot_date(df.index, df.values, '-')

axes.xaxis.set_major_locator(dates.HourLocator(byhour=range(0,24,2)))
axes.xaxis.set_minor_locator(dates.MinuteLocator(byminute=range(0,24*60,10)))
axes.xaxis.set_major_formatter(dates.DateFormatter('%H:%M'))

plt.show()

这篇关于从带有timedelta索引的 pandas 数据帧进行绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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