读取JSON后用Seaborn绘制多折线图出现空白图表,求解决
问题排查与修复方案
核心问题分析
- x轴数据无效:
x = [print(i) for i in range(1,7)]中print()函数返回None,导致x是一个全为None的列表,Seaborn无法识别有效轴数据,直接生成空白图。 - 缺少图表显示代码:绘制完成后没有调用
plt.show()来渲染并显示图表。 - 未完成多指标可视化:原代码仅绘制了
fed_acc,未实现fed_pre、fed_recall、fed_f1的多折线展示。
修复后的完整代码
import json import seaborn as sns import matplotlib.pyplot as plt import pandas as pd # 读取JSON文件 i = 16 with open(f"{i}_results.json", "r") as a_file: a_dictionary = json.load(a_file) # 提取数据并整理为DataFrame(更适合Seaborn可视化) data = a_dictionary['16'] x_values = list(range(1,7)) # 正确生成x轴数据:[1,2,3,4,5,6] # 构建DataFrame df = pd.DataFrame({ "x": x_values * 4, "value": data['fed_acc'] + data['fed_pre'] + data['fed_recall'] + data['fed_f1'], "metric": ["acc"]*6 + ["pre"]*6 + ["recall"]*6 + ["f1"]*6 }) # 设置绘图风格 sns.set_style("darkgrid") # 绘制多折线图 sns.lineplot(data=df, x="x", y="value", hue="metric", marker='o') # 添加图表标题和轴标签 plt.title("Federated Learning Metrics Over 6 Iterations") plt.xlabel("Iteration") plt.ylabel("Score") # 显示图表 plt.show()
关键修复点说明
- 修正x轴数据:用
list(range(1,7))生成有效x轴数值列表[1,2,3,4,5,6],替代原错误的列表推导式。 - 使用DataFrame组织数据:将四个指标的数据整合为长格式DataFrame,更符合Seaborn的API设计,简化多折线绘制逻辑。
- 添加图表显示语句:调用
plt.show()确保图表正常渲染显示。 - 完善图表元素:添加标题、轴标签,设置绘图风格提升可读性。
替代方案(不使用DataFrame)
如果不想用DataFrame,也可以逐个绘制每个指标:
import json import seaborn as sns import matplotlib.pyplot as plt i = 16 with open(f"{i}_results.json", "r") as a_file: a_dictionary = json.load(a_file) data = a_dictionary['16'] x_values = list(range(1,7)) sns.set_style("darkgrid") # 逐个绘制四个指标 sns.lineplot(x=x_values, y=data['fed_acc'], marker='o', color='navy', label='acc') sns.lineplot(x=x_values, y=data['fed_pre'], marker='s', color='red', label='pre') sns.lineplot(x=x_values, y=data['fed_recall'], marker='^', color='green', label='recall') sns.lineplot(x=x_values, y=data['fed_f1'], marker='*', color='orange', label='f1') plt.title("Federated Learning Metrics") plt.xlabel("Iteration") plt.ylabel("Score") plt.legend() plt.show()
内容的提问来源于stack exchange,提问作者Man.utd
相关产品推荐
相关产品推荐

