社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

有没有办法用plotly或python创建条形图可视化,其中y轴是24小时范围,x轴是所有工作日?

Tiffa • 4 年前 • 1956 次点击  

我正在尝试创建一组人的工作时间的可视化(最好是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()

plotly graph of above code

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

![上图#2][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?

以下是新的尝试:

employees = list(["Paige","Julissa","Jessica","David","Jamila","Eric Pt",
                 "Nicole","Jackie","Christian","McKay","Eric Pxt","Krissa",
              "Brynn","Jordan","Ethan","Andrew","Tysen","Austin","Dalin",
                "Alex","Pierce","Astha","Spencer","Edgar","Mike","Tiffany"])

df = pd.DataFrame(
    itertools.product(
        pd.date_range("18-oct-2021", periods=7, freq="D").values, employees
    ),
    columns=["date", "employee"],
)

csi_times=["8:00:00.00","11:00:00.00","8:00:00.00","9:00:00.00",
            "10:00:00.00","8:00:00.00","7:00:00.00","9:00:00.00",
            "8:00:00.00","14:30:00.00","9:00:00.00","7:00:00.00",
            "8:00:00.00","9:00:00.00","9:00:00.00","7:00:00.00",
            "22:00:00.00","22:00:00.00","9:00:00.00","15:00:00.00",
            "10:00:00.00","9:00:00.00","8:00:00.00","22:00:00.00",
            "10:00:00.00","7:30:00.00"]
times_format = '%H:%M:%S.%f'
worked_hours = []
n=8
for time in csi_times:
    given_times = datetime.strptime(time, date_format_str)
    final_times = given_times + timedelta(hours=n)
    final_time_strngs = final_times.strftime('%H:%M')
    worked_hours.append(final_time_strngs)
#print(csitimes)

df["start"]=csi_times*7

df["hoursworked"]= worked_hours*7

df["dow"]=df["date"].dt.strftime("%a")

#8,11,8,9,10,8,7,9,8,14,9,7,8,9,9,7,22,22,9,15,10,9,8,22,10,7
#create the figure as bar graph
fig = px.bar(df, x="dow", y="hoursworked", base="start", color="employee", barmode="group",
      labels={
                     "dow": "Days of Week",
                     "hoursworked": "Working Hours",
                     "employee": "CSI Team"
                 },
      title="CSI Working Hours")

#reverse y axis so it starts with 0 (12AM) and goes down to 23(11PM)
fig.update_layout(
   yaxis = dict(autorange = "reversed")
)
fig.show()

new plotly graph

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131642
文章 [ 2 ]  |  最新文章 4 年前
gboffi
Reply   •   1 楼
gboffi    5 年前

enter image description here

这里是一个非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()
Rob Raymond
Reply   •   2 楼
Rob Raymond    5 年前
  • 做你描述的事情很简单。按照你的描述,用 工作日、开始、工作时间、员工
  • 这就变成了一个简单的条形图 星期五 是 xaxis 和 亚克斯 显示开始时间和工作时间的酒吧
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")

enter image description here

数据帧样本

日期 受雇者 开始 工作时间 陶氏
2021-10-18 00:00:00 A. 3. 5. 周一
2021-10-18 00:00:00 B 3. 5. 周一
2021-10-18 00:00:00 C 4. 4. 周一
2021-10-19 00:00:00 A. 6. 6. 星期二
2021-10-19 00:00:00 B 1. 8. 星期二
2021-10-19 00:00:00 C 9 5. 星期二
2021-10-20 00:00:00 A. 7. 4. 结婚
2021-10-20 00:00:00 B 2. 4. 结婚
2021-10-20 00:00:00 C 1. 4. 结婚
2021-10-21 00:00:00 A. 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")