根据星期时间统计日期总量,绘制matplotlib,pandas,Python

x33g5p2x  于2022-08-17 转载在 Python  
字(2.9k)|赞(0)|评价(0)|浏览(715)

根据星期时间统计日期总量,绘制matplotlib图,pandas,Python

每一个日期都有一个对应的星期几日期,现在假设有很多随机的日期,然后逐一获取日期对应的星期几数字,然后统计所有日期的星期几出现次数,最终划入到星期一到星期日7个分类,绘制统计图表:

  1. import datetime
  2. import pandas as pd
  3. import matplotlib
  4. import matplotlib.pyplot as plt
  5. from random import randrange
  6. from datetime import timedelta
  7. # 生成随机测试时间数量
  8. from pprint import pprint
  9. SAMPLE_COUNT = 500
  10. SECTION = 'section'
  11. SUM = 'sum'
  12. # 在start和end两个日期之间生成一个随机日期
  13. def random_date(start, end):
  14. delta = end - start
  15. seconds_delta = (delta.days * 24 * 60 * 60) # 开始日期和结束日期之间相差的秒数
  16. random_seconds = randrange(seconds_delta)
  17. return start + timedelta(seconds=random_seconds)
  18. def my_time():
  19. times = []
  20. for i in range(7):
  21. times.append({SECTION: i, SUM: 0})
  22. # pprint(times)
  23. start_date = datetime.datetime(2000, 1, 1)
  24. end_date = datetime.datetime(2021, 12, 31)
  25. cnt = 0
  26. while cnt < SAMPLE_COUNT:
  27. random_d = random_date(start_date, end_date)
  28. weekday = random_d.weekday() # 0是星期一,6是星期日
  29. # pprint(f'{random_d.strftime("%Y-%m-%d")} {number_to_weekday(weekday)}')
  30. for tx in times:
  31. if tx[SECTION] == weekday:
  32. tx[SUM] = tx[SUM] + 1
  33. break
  34. cnt = cnt + 1
  35. return times
  36. def drawchart(df):
  37. myfont = matplotlib.font_manager.FontProperties(fname='C:\Windows\Fonts\msyh.ttc')
  38. plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
  39. plt.rc('font', family='YaHei', weight='bold')
  40. order = []
  41. name = []
  42. mem = []
  43. for d, i in zip(df.values, df.index):
  44. order.append(i)
  45. name.append(d[0])
  46. mem.append(int(d[1]))
  47. FONT_SIZE = 12
  48. fig, ax = plt.subplots(figsize=(15, 13))
  49. b = ax.barh(y=range(len(name)), width=mem, align='center', color='red')
  50. # 为横向水平的柱图右侧添加数据标签。
  51. i = 0
  52. for rect in b:
  53. w = rect.get_width()
  54. ax.text(x=w, y=rect.get_y() + rect.get_height() / 2, s='%d' % (int(w)),
  55. horizontalalignment='left', verticalalignment='center',
  56. fontproperties=myfont, fontsize=FONT_SIZE - 2, color='green')
  57. ax.text(x=w / 2, y=rect.get_y() + rect.get_height() / 2, s=str(order[i]),
  58. horizontalalignment='center', verticalalignment='center',
  59. fontproperties=myfont, fontsize=FONT_SIZE - 3, color='white')
  60. i = i + 1
  61. ax.set_yticks(range(len(name)))
  62. ax.set_yticklabels(name, fontsize=FONT_SIZE - 1, fontproperties=myfont)
  63. ax.invert_yaxis()
  64. ax.set_xlabel('数据', fontsize=FONT_SIZE + 2, fontproperties=myfont)
  65. ax.set_title('不同星期天的数据点总量统计排名', fontsize=FONT_SIZE + 2, fontproperties=myfont)
  66. # 不要横坐标上的label标签。
  67. plt.xticks(())
  68. # 清除四周的边框线
  69. ax.get_yaxis().set_visible(True)
  70. for spine in ["left", "top", "right", "bottom"]:
  71. ax.spines[spine].set_visible(False)
  72. plt.subplots_adjust(left=0.15) # 调整左侧边距
  73. # ax.margins(y=0.01) #缩放 zoom in
  74. ax.set_aspect('auto')
  75. plt.show()
  76. # 把数字0,1,2,3,4,5,6转换为星期*
  77. # 0为星期一,6为星期日,依次类推
  78. def number_to_weekday(number):
  79. zh = ['一', '二', '三', '四', '五', '六', '日']
  80. weekday = f'星期{zh[number]}'
  81. return weekday
  82. def data_to_char():
  83. times = my_time()
  84. # pprint(times)
  85. # 数据组装成pandas数据帧。
  86. pd_data = []
  87. for t in times:
  88. l = [number_to_weekday(t[SECTION]), t[SUM]]
  89. pd_data.append(l)
  90. col = ['星期*', '次数']
  91. df = pd.DataFrame(data=pd_data, columns=col)
  92. df = df.sort_values(by=col[1], axis=0, ascending=False) # 降序
  93. # 重置索引
  94. df = df.reset_index(drop=True)
  95. df.index = df.index + 1
  96. pprint(df.head(7))
  97. drawchart(df)
  98. if __name__ == '__main__':
  99. data_to_char()

输出:

  1. 星期* 次数
  2. 1 星期四 78
  3. 2 星期二 74
  4. 3 星期三 74
  5. 4 星期五 73
  6. 5 星期日 70
  7. 6 星期六 68
  8. 7 星期一 63

统计图表:

相关文章