import matplotlib.pyplot as plt import pandas as pd # 设置matplotlib支持中文显示 plt.rcParams["font.family"] = ["SimHei"]# 设置matplotlib支持中文显示 class BasicVisualizer: @staticmethod def save_to_excel(counter, filename="弹幕统计.xlsx"): """保存弹幕统计结果到Excel文件""" # 将Counter中的数据转换为DataFrame,取出现次数最多的弹幕(默认全部) # 列名分别为"弹幕内容"和"出现次数" df = pd.DataFrame(counter.most_common(), columns=["弹幕内容", "出现次数"]) # 保存DataFrame到Excel文件,不包含索引列 df.to_excel(filename, index=False) print(f"Excel保存完成: {filename}") return df @staticmethod def plot_top8(ai_counter, filename="前8弹幕.png"): """生成出现次数排名前8的AI相关弹幕柱状图并保存""" # 获取出现次数最多的前8条AI相关弹幕 top8 = ai_counter.most_common(8) # 若没有数据,则提示并返回 if not top8: print("无数据生成前8弹幕图") return # 提取弹幕内容和对应的出现次数 texts = [item[0] for item in top8] counts = [item[1] for item in top8] # 创建画布,设置大小为12x6 plt.figure(figsize=(12, 6)) # 绘制水平柱状图,使用自定义颜色 bars = plt.barh(texts, counts, color=["#D16721","#E40DEB", '#2196F3', '#f44336', '#FFC107', '#5E06EB',"#52F321", "#36f4d4"]) # 设置x轴标签 plt.xlabel("出现次数") # 设置图表标题 plt.title("AI相关弹幕Top8") # 逆序排列y轴(使出现次数最多的弹幕在最上方) plt.gca().invert_yaxis() # 为每个柱子添加数值标签 for bar in bars: width = bar.get_width() # 获取柱子宽度(即出现次数) # 在柱子右侧添加数值标签,垂直居中对齐 plt.text(width + 0, bar.get_y() + bar.get_height()/2, f"{width}", va="center") # 自动调整布局,避免元素重叠 plt.tight_layout() # 保存图表到文件,设置dpi为300以保证清晰度 plt.savefig(filename, dpi=300) # 显示图表 plt.show() print(f"前8弹幕图保存: {filename}")