如何根据第三个变量为散点标记上色

202 投票
4 回答
355364 浏览
提问于 2025-04-17 06:42

我想用matplotlib画一个散点图,让点的颜色根据第三个变量来变化。我已经快做到这个了:

plt.scatter(w, M, c=p, marker='s')

这里的w和M是数据点,而p是我想用来改变点颜色的变量。
不过我想用灰度来表示,而不是用颜色。有没有人能帮我一下?

4 个回答

17

有时候,你可能需要根据x值的情况来精确地绘制颜色。比如,你有一个数据表,里面有三种变量和一些数据点。你想要做的事情包括:

  • 把与物理变量'A'对应的数据点用红色标记。
  • 把与物理变量'B'对应的数据点用蓝色标记。
  • 把与物理变量'C'对应的数据点用绿色标记。

在这种情况下,你可能需要写一个简单的函数,把x值映射到对应的颜色名称,然后把这个颜色列表传递给plt.scatter命令。

x=['A','B','B','C','A','B']
y=[15,30,25,18,22,13]

# Function to map the colors as a list from the input list of x variables
def pltcolor(lst):
    cols=[]
    for l in lst:
        if l=='A':
            cols.append('red')
        elif l=='B':
            cols.append('blue')
        else:
            cols.append('green')
    return cols
# Create the colors list using the function above
cols=pltcolor(x)

plt.scatter(x=x,y=y,s=500,c=cols) #Pass on the list created by the function here
plt.grid(True)
plt.show()

根据x变量为散点图上色

33

在matplotlib中,灰色可以用一个0到1之间的数字字符串来表示。
比如说 c = '0.1'

然后你可以把你的第三个变量转换成这个范围内的值,用来给你的点上色。
在下面的例子中,我使用了点的y坐标作为决定颜色的值:

from matplotlib import pyplot as plt

x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [125, 32, 54, 253, 67, 87, 233, 56, 67]

color = [str(item/255.) for item in y]

plt.scatter(x, y, s=500, c=color)

plt.show()

enter image description here

214

其实你不需要手动设置颜色。你只需要指定一个灰度色图就可以了...

import numpy as np
import matplotlib.pyplot as plt

# Generate data...
x = np.random.random(10)
y = np.random.random(10)

# Plot...
plt.scatter(x, y, c=y, s=500) # s is a size of marker 
plt.gray()

plt.show()

在这里输入图片描述

如果你想要更多不同的颜色选择,可以在调用 scatter 时指定 cmap 这个参数。想要使用这些颜色的反转版本,只需在它们的名字后面加上 "_r"。比如说,用 gray_r 代替 gray。市面上已经有好几种现成的灰度色图可供选择(例如 graygist_yargbinary 等等)。

import matplotlib.pyplot as plt
import numpy as np

# Generate data...
x = np.random.random(10)
y = np.random.random(10)

plt.scatter(x, y, c=y, s=500, cmap='gray')
plt.show()

撰写回答