簡體   English   中英

有沒有辦法用 plotly 或 python 創建條形圖可視化,其中 y 軸是 24 小時范圍,x 軸是所有工作日?

[英]Is there a way to create a bar graph visualization with plotly or python where the y-axis is 24hour range and x-axis is all the weekdays?

我正在嘗試創建一組人的工作時間的可視化(理想情況下是 plotly,因為我想合並一個下拉欄,允許用戶在美國的時區之間切換並相應地調整時間)。 x 軸是工作日,y 軸是 24 小時范圍,條形圖將垂直向下(顯示某人在周一至周五上午 7 點至下午 3 點工作)並且可以與其他人的工作時間重疊(我知道我需要使用不透明度參數)。

到目前為止,我已經嘗試了很多東西,最接近的是以下代碼:

import plotly.graph_objects as go
import pandas as pd

# Initialize figure
fig = go.Figure()

week_days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

# Add Traces
fig.add_trace(
    go.Bar(x=week_days,
           name="Nicole",
           #line=dict(color="#33CFA5")
          ))
#fig.update_yaxes(strftime("%H:%M"))

fig.update_layout(
    updatemenus=[
        dict(
            active=0,
            buttons=list([
                dict(label="None",
                     method="update",
                     args=[{"visible": [True, False, True, False]},
                           {"title": "CSI Work Hours",
                            #"annotations": []
                           }]),
                dict(label="MT",
                     method="update",
                     args=[{"visible": [True, False, False, False]},
                           {"title": "MT",
                            #"annotations": high_annotations
                           }]),
                dict(label="PT",
                     method="update",
                     args=[{"visible": [False, False, True, True]},
                           {"title": "PT",
                            #"annotations": low_annotations
                           }]),
                dict(label="HT",
                     method="update",
                     args=[{"visible": [True, True, True, True]},
                           {"title": "HT",
                            #"annotations": high_annotations + low_annotations
                           }]),
            ]),
        )
    ])

# Set title
fig.update_layout(title_text="CSI")

fig.show()

上面代碼的繪圖

#create plot with days of week as x-axis, 24hr range as y-axis
fig, ax = plt.subplots(figsize=(15,15))
#ax.plot_date(start_date, end_date, ydate=True, xdate=False)

#number of days in week 7, set to x-axis to display all week days
l = range(0,7)
week_days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

# reformat axis ticks to only show hour/min on y-axis; label x-axis w/ week days
from matplotlib.dates import DateFormatter
from matplotlib.axis import Axis
ax.yaxis.set_major_formatter(DateFormatter('%H:%M'))
ax.yaxis.set_major_locator(HourLocator())
ax.invert_yaxis()
#ax.set_yticks(t)
ax.set_xticks(l)
ax.set_xticklabels(week_days)

上面代碼的 plot#2

對於實際數據點,我嘗試為每個人或每個時區創建字典,但我無法弄清楚如何為數據點繪制列表。

person1_hrs_dict = {'Monday' : [7,8,9,10,11,12,13,14,15],
              'Tuesday' : [7,8,9,10,11,12,13,14,15],
              'Wednesday' : [7,8,9,10,11,12,13,14,15],
              'Thursday' : [7,8,9,10,11,12,13,14,15],
              'Friday' : [7,8,9,10,11,12,13,14,15],
              'Saturday' : 0,
              'Sunday' : 0
             }
MT_hrs_dict = {"weekdays":["Monday", "Tuesday", "Wednesday",
 "Thursday", "Friday", "Saturday", "Sunday"],
"csi team": ["person1","person2",etc],
"work hours": []}
#I don't think MT_hrs_dict would work since some people work weekends and have some weekdays off.
#I think I'm overcomplicating it or maybe creating text document might be easier?
  • 做你所描述的很簡單。 已完成您所描述的工作,構建了一個包含星期幾、開始時間、工作時間、員工的數據
  • 這成為一個簡單的柱狀圖中,其中,星期幾X軸Y軸和一間酒吧,節目開始時間和工作時間
import itertools
import pandas as pd
import numpy as np
import plotly.express as px

employees = list("ABC")

df = pd.DataFrame(
    itertools.product(
        pd.date_range("18-oct-2021", periods=7, freq="D").values, employees
    ),
    columns=["date", "employee"],
).pipe(
    lambda d: d.assign(
        start=np.random.randint(1, 10, len(d)),
        hoursworked=lambda d: np.random.randint(3, 10, len(d)),
        dow=d["date"].dt.strftime("%a")
    )
)

px.bar(df, x="dow", y="hoursworked", base="start", color="employee", barmode="group")

在此處輸入圖片說明

數據框樣本

日期 員工 開始 工作時間 道指
2021-10-18 00:00:00 一種 3 5 星期一
2021-10-18 00:00:00 3 5 星期一
2021-10-18 00:00:00 C 4 4 星期一
2021-10-19 00:00:00 一種 6 6 周二
2021-10-19 00:00:00 1 8 周二
2021-10-19 00:00:00 C 9 5 周二
2021-10-20 00:00:00 一種 7 4 星期三
2021-10-20 00:00:00 2 4 星期三
2021-10-20 00:00:00 C 1 4 星期三
2021-10-21 00:00:00 一種 3 6 周四

在此處輸入圖片說明

這是一個非 Plotly 解決方案,只是 Matplotlib。

讀者可以理解如何在代碼中輕松計算正確的條間距和位置。

In [102]: import matplotlib.pyplot as plt
     ...: from random import randint
     ...: 
     ...: # faking some data
     ...: dow = 'Mon Tue Wed Thu Fri'.split()
     ...: emps = 'Concetta Laura Gerry Ceci'.split()
     ...: data = {e:{d:(randint(0,12),randint(6,12))for d in dow}for e in emps}
     ...: 
     ...: # computing the appropriate width of the bars
     ...: nbars = len(emps)
     ...: d = 0.25   # distance between bars in terms of the bar width
     ...: total_width = 0.80 # total width of the horizontal stack of bars
     ...: # total_width = nbars*w + (nbars-1)*d*w →
     ...: w = total_width/(nbars+(nbars-1)*d)
     ...: origin = -total_width/2
     ...: 
     ...: # Plotting
     ...: x = range(len(dow))
     ...: fig, ax = plt.subplots()
     ...: for n, (emp, hours) in enumerate(data.items()):
     ...:     xn = [_+origin+n*(1+d)*w for _ in x]
     ...:     bottoms, heights = zip(*hours.values())
     ...:     ax.bar(xn, heights, width=w,
     ...:            bottom=bottoms, align='edge', label=emp)
     ...: # add background to groups of bars
     ...: ax.bar(x, 24, (total_width+1)/2, bottom=0, zorder=0, alpha=0.15)
     ...: # fixing x tick labels
     ...: ax.set_xticks(range(len(dow)))
     ...: ax.set_xticklabels(dow)
     ...: # fix y axis
     ...: ax.set_ylim((-0.50, 24.50))
     ...: ax.set_yticks(range(0, 25, 2))
     ...: # 
     ...: fig.legend()
     ...: plt.show()

暫無
暫無

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

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