【问题标题】:Plotting from a pandas dataframe with a timedelta index从带有 timedelta 索引的 pandas 数据帧中绘图
【发布时间】: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


    【解决方案1】:

    虽然我不确切知道根本问题是什么,但似乎与使用的软件包版本有关。当我使用较旧的 python 发行版(matplotlib 1.5.1、numpy 1.11.1、pandas 0.18.1 和 python 2.7.12)运行您的示例时,我会得到一个没有刻度的图,就像您描述的那样。

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

    通过使用最近的 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()
    

    【讨论】:

    猜你喜欢
    • 2014-02-12
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    • 2018-01-13
    • 2021-12-20
    • 2019-08-12
    • 2022-11-25
    • 1970-01-01
    相关资源
    最近更新 更多