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

Matplotlib散点图中能否单独修改单个点的颜色?

Matplotlib散点图中能否单独修改单个点的颜色?

当然可以实现啦!我看了你写的猜数字代码,想让正确的那个尝试点在散点图里颜色不一样其实很简单,给你两种实用的解决方案~

先看看你原来的代码,问题出在一次性把所有点都用同一种样式绘制了,所以没法单独改某个点的颜色:

import random

import statistics

import matplotlib.pyplot as mpl

x = random.randint(1, 100)

i = 0

tries = []

z = 0

while True:
    i+=1
    y = random.randint(1, 100)
    tries.append(y)
    if y==x:
        y=z
        print(f"The computer got it right in {i} tries.")
        print(f"The number was {x}")
        break

print(tries)

mpl.plot(tries, tries, 'o')
mpl.show()

方案一:分两次绘图,单独突出正确点

这个方法最直观——先把所有错误的尝试点用默认颜色画出来,再单独绘制正确的那个点,给它指定不同的颜色(甚至可以调大标记尺寸让它更显眼):

import random
import matplotlib.pyplot as mpl

x = random.randint(1, 100)
i = 0
tries = []

while True:
    i += 1
    y = random.randint(1, 100)
    tries.append(y)
    if y == x:
        print(f"The computer got it right in {i} tries.")
        print(f"The number was {x}")
        break

print(tries)

# 先绘制所有错误的尝试,使用默认样式
mpl.plot(tries[:-1], tries[:-1], 'o')
# 单独绘制正确的尝试,用红色,标记放大一点更显眼
mpl.plot(tries[-1], tries[-1], 'ro', markersize=10)

mpl.show()

解释一下:因为你的tries列表最后一个元素就是正确的答案(循环结束前刚把它加进去),所以tries[:-1]就是所有错误的尝试,先画这些;再用'ro'指定红色圆形标记,单独画最后一个正确点,还可以通过markersize调大尺寸,让它一眼就能被注意到。


方案二:用scatter的颜色列表精准控制

如果你以后需要给多个点设置不同颜色,这种方法会更灵活。我们可以创建一个颜色列表,给每个点指定对应的颜色,最后传给scatter函数的c参数:

import random
import matplotlib.pyplot as mpl

x = random.randint(1, 100)
i = 0
tries = []

while True:
    i += 1
    y = random.randint(1, 100)
    tries.append(y)
    if y == x:
        print(f"The computer got it right in {i} tries.")
        print(f"The number was {x}")
        break

print(tries)

# 创建颜色列表,默认用matplotlib的蓝色,最后一个点设为红色
color_list = ['#1f77b4'] * len(tries)  # #1f77b4是matplotlib默认的蓝色代码
color_list[-1] = 'red'

# 用scatter绘制,传入颜色列表
mpl.scatter(tries, tries, c=color_list, marker='o')

mpl.show()

这种方法的好处是,你可以给任意位置的点设置不同颜色,比如如果以后想把前5次尝试设为灰色,只需要修改color_list对应的位置就行,非常灵活。

两种方法都能完美解决你的需求,选你觉得顺手的用就好~

备注:内容来源于stack exchange,提问作者pixelhy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 07:14:35