【问题标题】:Time Wheel in python3 pandaspython3 pandas中的时间轮
【发布时间】:2017-03-14 03:38:24
【问题描述】:

如何使用登录/注销事件时间创建类似于下面的时间轮?特别希望以时间轮方式将平均登录/注销时间与星期几相关联?下面的图片是一个示例,但我正在寻找时间在一周中的哪几天昼夜不停地在图片中显示。我有可用的 python 和包含登录时间的数据集。我还想将颜色与用户类型相关联,例如管理员与普通用户或类似的东西。关于如何实现这一点的任何想法都会很棒。

一些示例数据在下面的熊猫数据框中

df:

TimeGenerated        EventID  Username  Message
2012-04-01 00:00:13  4624     Matthew   This guy logged onto the computer for the first time today
2012-04-01 00:00:14  4624     Matthew   This guy authenticated for some stuff 
2012-04-01 00:00:15  4624     Adam      This guy logged onto the computer for the first time today
2012-04-01 00:00:16  4624     James     This guy logged onto the computer for the first time today
2012-04-01 12:00:17  4624     Adam      This guy authenticated for some stuff
2012-04-01 12:00:18  4625     James     This guy logged off the computer for the last time today
2012-04-01 12:00:19  4624     Adam      This guy authenticated for some stuff
2012-04-01 12:00:20  4625     Adam      This guy logged off the computer for the last time today 
2012-04-01 12:00:21  4625     Matthew   This guy logged off the computer for the last time today

【问题讨论】:

  • 如果这还不够,我明天可以清理一些数据@stackoverflow.com/users/3877338/johne
  • 也许来自@Weir_Doe 的this 是灵感的源泉?
  • 您可以从同心圆环图构建这样的图表,如下所示:stackoverflow.com/questions/33019879/…
  • 您是要将颜色与用户类型相关联,还是与此时的登录总数相关联,还是两者兼而有之?如果两者都有,那么您希望如何定义颜色?
  • 我将按用户名分组,然后按星期几分组,然后按小时分组,并计算登录和注销的发生次数,尝试将登录定义为绿色热图和蓝色作为注销的热图,我假设我将不得不为此构建两张单独的图片,我对此很好

标签: python python-3.x pandas matplotlib visualization


【解决方案1】:

基本上,您需要完成 2 个不相交的任务:

  • 创建要可视化的频率表
  • 定义一个函数来可视化给定的表格

对于第一项任务,我假设您只需要一个包含工作日和时间的数据透视表。我随机生成一个:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.cm as cm
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]
print(data.T)

看起来像这样。每个数字都是此时的登录计数器:

       Mon  Tue  Wed  Thu  Fri  Sat  Sun
col_0                                   
00:00   55   56   67   60   60   62   45
01:00   51   65   70   65   60   59   40
02:00   47   76   67   68   61   63   51
....

现在,让我们为这张桌子画轮子吧!它将由多个饼图组成:

# make a heatmap building function 
def pie_heatmap(table, cmap=cm.hot, vmin=None, vmax=None,inner_r=0.25, pie_args={}):
    n, m = table.shape
    vmin= table.min().min() if vmin is None else vmin
    vmax= table.max().max() if vmax is None else vmax

    centre_circle = plt.Circle((0,0),inner_r,edgecolor='black',facecolor='white',fill=True,linewidth=0.25)
    plt.gcf().gca().add_artist(centre_circle)
    norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)
    cmapper = cm.ScalarMappable(norm=norm, cmap=cmap)
    for i, (row_name, row) in enumerate(table.iterrows()):
        labels = None if i > 0 else table.columns
        wedges = plt.pie([1] * m,radius=inner_r+float(n-i)/n, colors=[cmapper.to_rgba(x) for x in row.values], 
            labels=labels, startangle=90, counterclock=False, wedgeprops={'linewidth':-1}, **pie_args)
        plt.setp(wedges[0], edgecolor='white',linewidth=1.5)
        wedges = plt.pie([1], radius=inner_r+float(n-i-1)/n, colors=['w'], labels=[row_name], startangle=-90, wedgeprops={'linewidth':0})
        plt.setp(wedges[0], edgecolor='white',linewidth=1.5)



plt.figure(figsize=(8,8))
pie_heatmap(data, vmin=-20,vmax=80,inner_r=0.2)

plt.show();

希望对您有所帮助。

【讨论】:

  • 您可以添加plt.setp( pie, width=width, edgecolor='white') 让它看起来更好吗? Ref link
  • 谢谢。我添加了内圈并增加了线宽。现在它更加美观和可读!
  • 谢谢。我可以说没有细线看起来更好,但内圈当然很好!
  • 嗯,用它们之间的边界区分具有非常相似颜色的相邻值将更加困难。但是由于 OP 的图像还包括边框,所以让我们保持这种状态
【解决方案2】:

从@DavidDale 的回答中生成数据,可以在极轴上绘制表格的pcolormesh 图。这将直接给出所需的情节。

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 2012-11-17
    • 2020-05-29
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 2018-09-28
    相关资源
    最近更新 更多