GenerateReport.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # -*- coding: utf-8 -*-
  2. """
  3. @author: zsc
  4. @time: 2024/11/18
  5. @desc: 报告生成
  6. """
  7. import time
  8. import random
  9. from collections import defaultdict
  10. import matplotlib.pyplot as plt
  11. plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
  12. plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
  13. # 报告生成模块(续)
  14. class ReportGenerator:
  15. def __init__(self, data, anomalies, segments, action_stats, product_stats, channel_stats):
  16. self.data = data
  17. self.anomalies = anomalies
  18. self.segments = segments
  19. self.action_stats = action_stats
  20. self.product_stats = product_stats
  21. self.channel_stats = channel_stats
  22. def generate(self):
  23. # 生成用户行为报告,并展示成图表形式
  24. report = {
  25. 'total_users': len(set([item['user'] for item in self.data])),
  26. 'total_actions': len(self.data),
  27. 'anomalies': self.anomalies,
  28. 'user_segments': self.segments,
  29. 'action_stats': self.action_stats,
  30. 'product_stats': self.product_stats,
  31. 'channel_stats': self.channel_stats
  32. }
  33. self.plot_action_stats(self.action_stats)
  34. self.plot_product_stats(self.product_stats)
  35. self.plot_channel_stats(self.channel_stats)
  36. return report
  37. def plot_action_stats(self, action_stats):
  38. if not action_stats:
  39. print("No data for action stats.")
  40. return
  41. # 生成行为统计图表
  42. actions = list(action_stats.keys())
  43. counts = list(action_stats.values())
  44. plt.figure(figsize=(12, 8)) # 调整图表大小
  45. plt.bar(actions, counts, color='skyblue')
  46. plt.xlabel('行为', fontsize=12) # 调整字体大小
  47. plt.ylabel('次数', fontsize=12)
  48. plt.title('行为统计', fontsize=14)
  49. plt.xticks(rotation=45, fontsize=10) # 旋转刻度标签并调整字体大小
  50. plt.yticks(fontsize=10)
  51. plt.tight_layout() # 自动调整布局
  52. # 如果需要,可以手动调整边距
  53. # plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1)
  54. plt.show()
  55. def plot_product_stats(self, product_stats):
  56. if not product_stats:
  57. print("No data for product stats.")
  58. return
  59. # 生成产品统计图表
  60. products = list(product_stats.keys())
  61. counts = list(product_stats.values())
  62. plt.figure(figsize=(10, 6))
  63. plt.bar(products, counts, color='lightgreen')
  64. plt.xlabel('产品')
  65. plt.ylabel('次数')
  66. plt.title('产品统计')
  67. plt.show()
  68. def plot_channel_stats(self, channel_stats):
  69. if not channel_stats:
  70. print("No data for channel stats.")
  71. return
  72. # 生成渠道统计图表
  73. channels = list(channel_stats.keys())
  74. counts = list(channel_stats.values())
  75. plt.figure(figsize=(10, 6))
  76. plt.bar(channels, counts, color='orange')
  77. plt.xlabel('渠道')
  78. plt.ylabel('次数')
  79. plt.title('渠道统计')
  80. plt.show()