【发布时间】:2017-05-09 03:31:09
【问题描述】:
我正在尝试从带有 timedelta 索引的 pandas 数据框中绘制一些数据,并且我想自定义 x 轴中的时间刻度和标签。这应该很简单,但事实证明这是一项艰巨的工作。
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 分钟添加一次次要刻度?
【问题讨论】:
标签: python pandas matplotlib