我想制作一个散点图(使用 matplotlib),其中点根据第三个变量进行着色。我已经非常接近这个了:
plt.scatter(w, M, c=p, marker='s')
其中 w 和 M 是数据点,p 是我想要相对于其进行着色的变量。
不过我想用灰度而不是彩色来做。有人可以帮忙吗?
无需手动设置颜色。相反,指定灰度颜色图...
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()
或者,如果您想要更广泛的颜色图,您也可以将
cmap
kwarg 指定为 scatter
。要使用其中任何一个的反向版本,只需指定其中任何一个的“_r
”版本。例如。 gray_r
而不是gray
。预先制作了几种不同的灰度颜色图(例如 gray
、gist_yarg
、binary
等)。
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()
在 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()
有时您可能需要根据 x 值情况精确绘制颜色。例如,您可能有一个包含 3 种类型的变量和一些数据点的数据框。并且您想做以下事情,
在这种情况下,您可能需要编写短函数以将 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()
一个非常简单的解决方案也是这个:
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8,8))
p = ax.scatter(x, y, c=y, cmap='cmo.deep')
fig.colorbar(p,ax=ax,orientation='vertical',label='labelname')