【问题标题】:How to create a graph representing multiple time invervals per day如何创建表示每天多个时间间隔的图表
【发布时间】:2019-04-22 00:34:17
【问题描述】:

鉴于以下 dict 包含每天的开/关时间对:

timetable = {
    'monday': ['08:00', '12:00', '13:00', '18:00'],
    'tuesday': ['08:00', '12:00', '13:00', '18:00'],
    'wednesday': ['08:00', '12:00', '13:00', '18:00'],
    'thursday': ['08:00', '12:00', '13:00', '18:00'],
    'friday': ['08:00', '12:00', '13:00', '18:00', '19:00', '23:00'],
    'saturday': ['10:00', '16:00'],
    'sunday': ['10:00', '16:00'],
}

有没有办法创建一个看起来像 https://imgur.com/a/lK8CT9P 的图形表示(这是用 gimp 完成的,只是为了大致了解它的样子)?

【问题讨论】:

标签: python matplotlib graph


【解决方案1】:

试试这样的。

import matplotlib.pyplot as plt
import datetime
timetable = {
  'monday': ['08:00', '12:00', '13:00', '18:00'],
  'tuesday': ['08:00', '12:00', '13:00', '18:00'],
  'wednesday': ['08:00', '12:00', '13:00', '18:00'],
  'thursday': ['08:00', '12:00', '13:00', '18:00'],
  'friday': ['08:00', '12:00', '13:00', '18:00', '19:00', '23:00'],
  'saturday': ['10:00', '16:00'],
  'sunday': ['10:00', '16:00'],
}
COLOR_LIST = ['blue', 'red', 'green', 'pink', 'brown', 'orange', 'yellow']
HEIGHT = 2
fig, ax = plt.subplots()
y_parameter = 0
for day, day_data in timetable.iteritems():
    st = [datetime.datetime.strptime(i, "%H:%M") for i in day_data[::2]]
    et = [datetime.datetime.strptime(i, "%H:%M") for i in day_data[1::2]]
    color = COLOR_LIST.pop()
    for start_time, end_time in zip(st, et):
        diff = (end_time - start_time).total_seconds()
        x_paramter = datetime.timedelta(hours=start_time.hour, minutes=start_time.minute,
                                    seconds=start_time.second).total_seconds()
        ax.add_patch(plt.Rectangle((x_paramter, y_parameter), int(diff), HEIGHT, facecolor=color))
        centerx = x_paramter + 100
        centery = y_parameter + 1
        plt.text(centerx, centery, day, fontsize=5, wrap=True)
        plt.text(centerx, centery - 1, str(int(diff)), fontsize=5, wrap=True)
    ax.autoscale()
    ax.set_ylim(0, 24)
    y_parameter += 3
plt.show()

输出类似于:

【讨论】:

  • 您好,感谢您的回答。您使用切片运算符获取stet 的方式对我来说特别有趣(作为Python 初学者)。如何处理交换xy 轴以便在x 轴上有几天?至于刻度,您将如何设置标签分别代表小时(假设 HH:MM 不是简单的int)和天?
  • @user11392621 你将不得不玩弄它:) 这是可行的:)
猜你喜欢
  • 1970-01-01
  • 2021-11-30
  • 2023-04-02
  • 1970-01-01
  • 2015-04-20
  • 1970-01-01
  • 1970-01-01
  • 2020-09-22
  • 2015-05-30
相关资源
最近更新 更多