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

基于Python Matplotlib实现按字典键分组的散点图着色

按类别为散点着色并添加图例的解决方案

嘿,我来帮你搞定这个按字典键给散点分组着色的问题!其实不用绕远路,两种简单方法就能实现你的需求,我给你详细拆解一下:

方法一:直接用Matplotlib遍历(无需额外库)

这个方法完全贴合你原来的代码逻辑,只需要在遍历每个类别时,一次性绘制该类别的所有点并指定标签,最后添加图例即可:

import matplotlib.pyplot as plt

# 替换成你的实际数据
data = {
    '15': [{'x': 1, 'y': 2}, {'x': 3, 'y': 4}, {'x': 5, 'y': 6}],
    '16': [{'x': 2, 'y': 3}, {'x': 4, 'y': 5}, {'x': 6, 'y': 7}],
    '17': [{'x': 0, 'y': 1}, {'x': 2, 'y': 0}, {'x': 4, 'y': 2}]
}

fig, ax = plt.subplots()

# 遍历每个类别,绘制对应点并设置标签
for category, points in data.items():
    # 提取当前类别的x、y值列表
    x_vals = [p['x'] for p in points]
    y_vals = [p['y'] for p in points]
    # 绘制散点,label参数对应图例显示的文本
    ax.scatter(x_vals, y_vals, label=category)

# 添加图例,title可以设置图例的标题
ax.legend(title='Category')
plt.show()

为什么这个方法有效?

每次调用scatter时,Matplotlib会自动为不同的系列分配不同的颜色,而label参数会把当前类别和这个颜色绑定,最后ax.legend()会自动把所有标签和对应的颜色整理成图例。


方法二:用Pandas整理数据后绘制(更适合复杂数据集)

你之前尝试用Pandas的方向是对的,但没把数据转换成正确的格式。我们需要把数据转成长格式DataFrame(每一行对应一个点,包含x、y、类别三列),这样就能轻松按类别着色:

import matplotlib.pyplot as plt
import pandas as pd

# 替换成你的实际数据
data = {
    '15': [{'x': 1, 'y': 2}, {'x': 3, 'y': 4}, {'x': 5, 'y': 6}],
    '16': [{'x': 2, 'y': 3}, {'x': 4, 'y': 5}, {'x': 6, 'y': 7}],
    '17': [{'x': 0, 'y': 1}, {'x': 2, 'y': 0}, {'x': 4, 'y': 2}]
}

# 把原始字典转换成长格式DataFrame
df_rows = []
for category, points in data.items():
    for point in points:
        # 给每个点添加类别字段
        df_rows.append({'x': point['x'], 'y': point['y'], 'category': category})
df = pd.DataFrame(df_rows)

# 绘制散点,用category字段区分颜色
fig, ax = plt.subplots()
scatter = ax.scatter(df['x'], df['y'], c=df['category'], cmap='viridis')

# 手动创建图例(因为c参数用字符串类别时,Matplotlib不会自动生成图例)
ax.legend(
    handles=scatter.legend_elements()[0],
    labels=data.keys(),
    title='Category'
)
plt.show()

更简洁的Seaborn版本

如果愿意用Seaborn库,代码会更简洁,它会自动处理图例:

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

# 同上的df创建过程
sns.scatterplot(data=df, x='x', y='y', hue='category')
plt.legend(title='Category')
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 06:55:34