179

我想制作一个散点图(使用 matplotlib),其中的点根据第三个变量进行着色。我对此非常接近:

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

其中 w 和 M 是数据点,p 是我要对其进行着色的变量。
但是我想用灰度而不是彩色来做。任何人都可以帮忙吗?

4

3 回答 3

193

无需手动设置颜色。相反,请指定灰度颜色图...

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)
plt.gray()

plt.show()

在此处输入图像描述

或者,如果您喜欢更广泛的颜色图,您还可以将cmapkwarg 指定为scatter. 要使用其中任何一个的反转版本,只需指定其中_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()
于 2011-11-20T21:43:19.207 回答
30

在 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()

在此处输入图像描述

于 2011-11-20T16:43:33.467 回答
12

有时您可能需要根据 x 值大小写精确地绘制颜色。例如,您可能有一个包含 3 种类型变量和一些数据点的数据框。你想做以下事情,

  • 绘制与 RED 中的物理变量“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 变量的函数

于 2018-07-16T20:48:46.483 回答