# -*- coding: utf-8 -*- """ @author: zsc @time: 2024/11/18 @desc: 报告生成 """ import time import random from collections import defaultdict import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签 plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号 # 报告生成模块(续) class ReportGenerator: def __init__(self, data, anomalies, segments, action_stats, product_stats, channel_stats): self.data = data self.anomalies = anomalies self.segments = segments self.action_stats = action_stats self.product_stats = product_stats self.channel_stats = channel_stats def generate(self): # 生成用户行为报告,并展示成图表形式 report = { 'total_users': len(set([item['user'] for item in self.data])), 'total_actions': len(self.data), 'anomalies': self.anomalies, 'user_segments': self.segments, 'action_stats': self.action_stats, 'product_stats': self.product_stats, 'channel_stats': self.channel_stats } self.plot_action_stats(self.action_stats) self.plot_product_stats(self.product_stats) self.plot_channel_stats(self.channel_stats) return report def plot_action_stats(self, action_stats): if not action_stats: print("No data for action stats.") return # 生成行为统计图表 actions = list(action_stats.keys()) counts = list(action_stats.values()) plt.figure(figsize=(12, 8)) # 调整图表大小 plt.bar(actions, counts, color='skyblue') plt.xlabel('行为', fontsize=12) # 调整字体大小 plt.ylabel('次数', fontsize=12) plt.title('行为统计', fontsize=14) plt.xticks(rotation=45, fontsize=10) # 旋转刻度标签并调整字体大小 plt.yticks(fontsize=10) plt.tight_layout() # 自动调整布局 # 如果需要,可以手动调整边距 # plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1) plt.show() def plot_product_stats(self, product_stats): if not product_stats: print("No data for product stats.") return # 生成产品统计图表 products = list(product_stats.keys()) counts = list(product_stats.values()) plt.figure(figsize=(10, 6)) plt.bar(products, counts, color='lightgreen') plt.xlabel('产品') plt.ylabel('次数') plt.title('产品统计') plt.show() def plot_channel_stats(self, channel_stats): if not channel_stats: print("No data for channel stats.") return # 生成渠道统计图表 channels = list(channel_stats.keys()) counts = list(channel_stats.values()) plt.figure(figsize=(10, 6)) plt.bar(channels, counts, color='orange') plt.xlabel('渠道') plt.ylabel('次数') plt.title('渠道统计') plt.show()