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

如何绘制4个条件区间各对应不同颜色的Python散点图

错误原因

原代码无法实现预期效果的核心问题有两个:

  • pandas.DataFrame.plot()的x、y参数仅接受数据框中已存在的列名,不支持直接在参数位置写入行筛选表达式,不会自动按你写的条件过滤数据
  • 传入的颜色值light blue、dark blue包含空格,不符合matplotlib的颜色命名规则,无法被正确解析。
方案1:按分区筛选子集绘图(和你原有逻辑一致)

这是最直观的实现方式,直接按你定义的四个分区先过滤出对应的数据子集,再分别绘制散点:

ax = pintar_campo('grey')

# 区域1:x <= 17
df_suarez[df_suarez['x'] <= 17].plot(
    kind='scatter',
    x='x',
    y='y',
    color='lightblue',
    ax=ax,
    label='x ≤ 17'
)
# 区域2:17 < x <= 50
df_suarez[(df_suarez['x'] > 17) & (df_suarez['x'] <= 50)].plot(
    kind='scatter',
    x='x',
    y='y',
    color='blue',
    ax=ax,
    label='17 < x ≤ 50'
)
# 区域3:50 < x <= 83
df_suarez[(df_suarez['x'] > 50) & (df_suarez['x'] <= 83)].plot(
    kind='scatter',
    x='x',
    y='y',
    color='darkblue',
    ax=ax,
    label='50 < x ≤ 83'
)
# 区域4:x > 83
df_suarez[df_suarez['x'] > 83].plot(
    kind='scatter',
    x='x',
    y='y',
    color='purple',
    ax=ax,
    label='x > 83'
)

ax.set_title("Los eventos de Luís Suárez")
ax.legend() # 不需要图例可以删掉这行
方案2:分箱后统一绘图(更易维护)

如果后续需要调整分区边界、颜色,推荐用pandas的cut方法先给数据做分箱标记,再遍历分区绘图,不需要重复写筛选逻辑:

ax = pintar_campo('grey')

# 统一配置分区边界、对应颜色、图例标签
bins = [-float('inf'), 17, 50, 83, float('inf')]
color_map = {
    'x ≤ 17': 'lightblue',
    '17 < x ≤ 50': 'blue',
    '50 < x ≤ 83': 'darkblue',
    'x > 83': 'purple'
}

# 给每条数据打分区标签
df_suarez['zone'] = pd.cut(
    df_suarez['x'],
    bins=bins,
    labels=list(color_map.keys())
)

# 遍历每个分区绘图
for zone_name, color in color_map.items():
    zone_data = df_suarez[df_suarez['zone'] == zone_name]
    zone_data.plot(
        kind='scatter',
        x='x',
        y='y',
        color=color,
        ax=ax,
        label=zone_name
    )

ax.set_title("Los eventos de Luís Suárez")
ax.legend()
注意事项
  • 多条件筛选DataFrame时,每个独立判断条件必须用圆括号包裹,用&表示逻辑与、|表示逻辑或,不能直接用Python原生的and/or关键字,否则会触发运算优先级报错
  • 如果需要更精准的自定义配色,可以把color参数替换为十六进制色值(比如#aec7e8)或者0-1范围的RGB元组
  • 代码中的label参数和ax.legend()是可选配置,不需要显示图例可以直接删除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 20:27:15