Python多ID数据集同图绘制:a为x轴、b为y轴的散点图实现
批量绘制多ID散点图的正确实现
咱们先拆解下你代码里的问题:
- 你用
id的值(比如1、2)去索引列表information,但列表的索引是从0开始的,这会直接导致索引越界错误——毕竟你的列表只有2个元素,合法索引只能是0和1。 - 每次循环里都调用
plt.show(),这会让每个ID的散点图单独弹出一个窗口,而不是合并到同一张图里展示。
下面给你两种实用的解决方案:
方案一:直接遍历数据集列表
这是最简洁的方式,不需要依赖id值,直接逐个处理列表里的每个数据项:
import matplotlib.pyplot as plt import numpy as np # 补全数据集的numpy数组定义 Information = [ {'id' : 1, 'a' : np.array([0.7, 0.5 , 0.20 , 0.48 , 0.79]), 'b' : np.array([0.1, 0.5 , 0.96 , 0.08 , 0.7])}, {'id' : 2, 'a' : np.array([0.37, 0.55 , 0.27 , 0.47 , 0.79]), 'b' : np.array([0.1, 0.5 , 0.9 , 0.87 , 0.7])} ] # 遍历每个数据条目 for item in Information: a_data = item['a'] b_data = item['b'] # 添加label,方便在图例中区分不同ID plt.scatter(a_data, b_data, label=f"ID: {item['id']}") # 完善图表细节 plt.xlabel('a') plt.ylabel('b') plt.title('Scatter Plot for All IDs') plt.legend() # 显示图例,区分不同ID的点 plt.show() # 最后统一显示整张图表
方案二:用ID映射字典(适合ID不连续的场景)
如果后续你的数据集ID可能不是连续数字,或者列表顺序和ID顺序不一致,可以先把数据集转换成以ID为键的字典,再遍历:
import matplotlib.pyplot as plt import numpy as np Information = [ {'id' : 1, 'a' : np.array([0.7, 0.5 , 0.20 , 0.48 , 0.79]), 'b' : np.array([0.1, 0.5 , 0.96 , 0.08 , 0.7])}, {'id' : 2, 'a' : np.array([0.37, 0.55 , 0.27 , 0.47 , 0.79]), 'b' : np.array([0.1, 0.5 , 0.9 , 0.87 , 0.7])} ] # 转换为以ID为键的字典,方便通过ID直接取数 info_dict = {entry['id']: entry for entry in Information} # 遍历所有ID for id_num in info_dict: current_data = info_dict[id_num] plt.scatter(current_data['a'], current_data['b'], label=f"ID: {id_num}") plt.xlabel('a') plt.ylabel('b') plt.title('Scatter Plot for All IDs') plt.legend() plt.show()
这两种方案都能把所有ID的散点绘制在同一张图里,并且通过图例清晰区分不同ID的数据。
内容的提问来源于stack exchange,提问作者jig
相关产品推荐
相关产品推荐

