简体   繁体   English

从带有timedelta索引的熊猫数据帧进行绘图

[英]Plotting from a pandas dataframe with a timedelta index

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. 我正在尝试从带有timedelta索引的pandas数据框中绘制一些数据,我想在x轴上自定义时间刻度和标签。 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()

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? 例如,如何每两个小时添加一次大刻度线和标签,并每隔10分钟添加一次小刻度线?

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. 当我使用较旧的python发行版(matplotlib 1.5.1,numpy 1.11.1,pandas 0.18.1和python 2.7.12)运行示例时,正如您所描述的,我得到的图没有刻度线。

However I can get a plot with the correct ticks 但是我可以获得正确的刻度图

用正确的滴答作答

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). 通过使用最新的python发行版(matplot 2.0.1,numpy 1.12.1,pandas 0.19.1和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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM