Time Wheel in python3 pandas

前端 未结 2 1297
清歌不尽
清歌不尽 2021-02-13 10:07

How can I create a timewheel similar to below with logon/logoff event times? Specifically looking to correlate mean login/logoff time correlated to the day of the week in a time

2条回答
  •  借酒劲吻你
    2021-02-13 11:03

    Taking the data generation from @DavidDale's answer, one may plot a pcolormesh plot of the table on a polar axes. This would directly give the desired plot.

    import pandas as pd
    import matplotlib.pyplot as plt
    import numpy as np
    import calendar
    
    # generate the table with timestamps
    np.random.seed(1)
    times = pd.Series(pd.to_datetime("Nov 1 '16 at 0:42") + 
                      pd.to_timedelta(np.random.rand(10000)*60*24*40, unit='m'))
    # generate counts of each (weekday, hour)
    data = pd.crosstab(times.dt.weekday, 
                       times.dt.hour.apply(lambda x: '{:02d}:00'.format(x))).fillna(0)
    data.index = [calendar.day_name[i][0:3] for i in data.index]
    data = data.T
    
    # produce polar plot
    fig, ax = plt.subplots(subplot_kw=dict(projection='polar'))
    ax.set_theta_zero_location("N")
    ax.set_theta_direction(-1)
    
    # plot data
    theta, r = np.meshgrid(np.linspace(0,2*np.pi,len(data)+1),np.arange(len(data.columns)+1))
    ax.pcolormesh(theta,r,data.T.values, cmap="Reds")
    
    # set ticklabels
    pos,step = np.linspace(0,2*np.pi,len(data),endpoint=False, retstep=True)
    pos += step/2.
    ax.set_xticks(pos)
    ax.set_xticklabels(data.index)
    
    ax.set_yticks(np.arange(len(data.columns)))
    ax.set_yticklabels(data.columns)
    plt.show()
    

提交回复
热议问题