簡體   English   中英

如何使用 pandas 和 plotly 按天計算 plot 值的頻率?

[英]How to plot the frequency of values by day with pandas and plotly?

我想 plot 使用 pandas 和 plotly 的條形圖顯示玩家一天的頻率,同時,我可以過濾級別圖顯示的“級別”條形圖,以便我過濾結果顯示。 我還希望所有 7 天都以有序的方式顯示在 x 軸上。 非常感謝您的幫助!

下面是我的代碼:

# data lists
day = ['Monday','Wednesday','Sunday','Wednesday']
level = ['Level 5','Level 2','Level 1','Level 2']
score = ['50','20','10','25']
player = ['Tom','Sam','Bill','Max']

# create new dataframe and insert desired columns
df = pd.DataFrame({'day':day,
                    'level':level,
                    'score':score,
                    'player':player})
df

我希望 output 是這樣的: 按日期划分的玩家頻率圖

下面的完整片段將使用按鈕按級別過濾您的數據集,並在 x 軸上按天顯示玩家數量。 這樣做的本質是:

  1. 使用pd.Categorical(df['day'], categories=new_order, ordered=True)將日期設置為有序類別,
  2. 通過df['level'].unique()拆分數據並使用fig.add_bar()分配跟蹤,
  3. 通過visibility = [list(s) for s in [e==1 for e in np.eye(len(levels))]]設置每個跟蹤的可見性

Plot 1

在此處輸入圖像描述

Plot 2

在此處輸入圖像描述

如您所見,我在您的數據集中添加了一些細節,使其更有趣。

完整代碼:

import pandas as pd
import numpy as np
import plotly.graph_objects as go

# data lists
day = ['Monday','Wednesday','Sunday','Wednesday', 'Tuesday']
level = ['Level 5','Level 2','Level 1','Level 2', 'Level 2']
score = ['50','20','10','25', '25']
player = ['Tom','Sam','Bill','Max', 'Sam']

# create new dataframe and insert desired columns
df = pd.DataFrame({'day':day,
                    'level':level,
                    'score':score,
                    'player':player})

# plotly setup
fig = go.Figure()

# data management
# - grouping
# - setiing up visibility attributes for groups
# - treat days as categorical variable
levels = df['level'].unique()[::-1]
nlevels = len(levels)
visibility = [list(s) for s in [e==1 for e in np.eye(len(levels))]]

new_order = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
df['day'] = pd.Categorical(df['day'], categories=new_order, ordered=True)

buttons = [] # container for buttons in updatemenu

# split data by levels,
# and add button per level
# with counts of players per day
# in an orderly fashion
for i, l in enumerate(levels):
    ds = df[df['level']==l]
    dg = ds.groupby('day').agg({'player':'count'}).reset_index()

    fig.add_bar(x = dg['day'], y = dg['player'],
                visible=True if l=='Level 1' else False)
    
    
    # one button per dataframe to trigger the visibility
    # of all columns / traces for each dataframe
    button =  dict(label=l,
                   method = 'restyle',
                   args = ['visible',visibility[i]])
    buttons.append(button)

# include dropdown updatemenu in layout
fig.update_layout(updatemenus=[dict(type="dropdown",
                                    direction="down",
                                    buttons = buttons)])
    
fig.show()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM