我正在嘗試創建一組人的作業時間的可視化(理想情況下是 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)

對于實際資料點,我嘗試為每個人或每個時區創建字典,但我無法弄清楚如何為資料點繪制串列。
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?
uj5u.com熱心網友回復:

這是一個非 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()
uj5u.com熱心網友回復:
- 做你所描述的很簡單。已完成您所描述的作業,構建了一個包含星期幾、開始時間、作業時間、員工的資料框
- 這成為一個簡單的柱狀圖中,其中,星期幾是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 | 周四 |
資料框構建 - 更簡單的語法
df = pd.DataFrame(
itertools.product(
pd.date_range("18-oct-2021", periods=7, freq="D").values, employees
),
columns=["date", "employee"],
)
df["start"] = np.random.randint(1, 10, len(df))
df["hoursworked"] = np.random.randint(3, 10, len(df))
df["dow"] = df["date"].dt.strftime("%a")
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/331266.html
標籤:Python matplotlib 阴谋 情节地
上一篇:如何為每組線添加單個圖例標簽
