You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何遍历字典中嵌套列表的所有索引并绘制散点图?

问题描述

我创建了如下字典mean_task_dict,包含三个键,每个键对应一个列表,每个列表包含48个数值:

mean_task_dict = {
            "Interoception": task_mean_intero,
            "Exteroception": task_mean_extero,
            "Cognitive": task_mean_cognit,
            }

我想要绘制散点图,x轴为三个类别ROI_positions = np.array([1, 2, 3]),字典中的每个列表需对应ROI_positions中的一个类别。

我的当前尝试代码如下:

import numpy as np
import matplotlib.pyplot as plt

task_mean_intero = [-0.28282956438352846, -0.33826908282117457, -0.23669673649758388]
task_mean_extero = [-0.3306686353702893, -0.4675910056474869, -0.2708033871055369]
task_mean_cognit = [-0.3053766849270014, -0.41698707094527254, -0.35655464189810543]

mean_task_dict = {
    "Interoception": task_mean_intero,
    "Exteroception": task_mean_extero,
    "Cognitive": task_mean_cognit,
    }

for value in mean_task_dict.values():
    ROI_positions = np.array([1, 2, 3])
    
    data_ROIs = np.array([
                         mean_task_dict["Interoception"][1],
                         mean_task_dict["Exteroception"][1],
                         mean_task_dict["Cognitive"][1]
                         ])
    
    plt.scatter(ROI_positions, data_ROIs)

目前的问题是,我只能通过指定每个列表的第二个索引[1]来计算和绘制单个值的数据,请问如何遍历字典中三个列表内的所有值,将它们全部绘制在同一幅图中?

解决方案

你当前的代码循环逻辑存在问题:每次循环都固定取各列表的第2个元素(索引[1]),且重复绘制同一组点,没有遍历所有元素。

正确的思路是:每个任务对应一个固定的x轴位置(比如Interoception对应x=1,Exteroception对应x=2,Cognitive对应x=3),然后把该任务列表里的所有数值都以这个x值为横坐标绘制散点。

修改后的代码如下:

import numpy as np
import matplotlib.pyplot as plt

# 示例数据(实际为48个数值,此处用3个示例)
task_mean_intero = [-0.28282956438352846, -0.33826908282117457, -0.23669673649758388]
task_mean_extero = [-0.3306686353702893, -0.4675910056474869, -0.2708033871055369]
task_mean_cognit = [-0.3053766849270014, -0.41698707094527254, -0.35655464189810543]

mean_task_dict = {
    "Interoception": task_mean_intero,
    "Exteroception": task_mean_extero,
    "Cognitive": task_mean_cognit,
}

# 定义每个任务对应的x轴位置
ROI_positions = [1, 2, 3]
task_names = list(mean_task_dict.keys())

# 遍历每个任务及其对应的x位置
for task_name, x_pos in zip(task_names, ROI_positions):
    # 获取当前任务的所有数值
    values = mean_task_dict[task_name]
    # 生成与数值列表长度匹配的x坐标列表,绘制散点
    plt.scatter([x_pos] * len(values), values, label=task_name)

# 优化图表可读性
plt.legend()
plt.xticks(ROI_positions, task_names)  # 将x轴刻度替换为任务名称
plt.xlabel("任务类别")
plt.ylabel("数值")
plt.title("各任务数值散点图")

plt.show()

关键说明

  • 用zip将任务名称与对应的x轴位置绑定,确保每个任务对应正确的横坐标
  • 对每个任务,生成与数值列表长度一致的x坐标列表([x_pos] * len(values)),让列表内所有数值都能以对应x位置绘制
  • 添加图例和自定义x轴刻度,提升图表的可读性

内容的提问来源于stack exchange,提问作者Philipp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 21:40:49