matplotlib 散点图中的颜色问题

color issue in scatter plot with matplotlib

这个很好用

import matplotlib.pyplot as plt
import numpy as np

y= [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
x= [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]
area= [0.78, 0.81, 0.78, 0.81, 0.78, 0.81, 0.787, 0.81, 0.99, 0.999, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99]
area = np.array(area)
area = area*2000

cluster = ['*','.','<','>','o','p','H','D','1','2','o','*','*','o','o','o']

fig,ax = plt.subplots()

for xp, yp, m in zip(x, y, cluster):
    ax.scatter(xp, yp,  s=area , marker = m)

plt.show()

但是当我尝试添加色谱时:

import matplotlib.pyplot as plt
import numpy as np

y= [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
x= [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]
colors= [286.135, 288.556, 286.135, 288.55, 286.13, 288.55627, 286.13, 288.556, 342.713, 333.98, 342.713, 333.9834, 342.713, 333.9834, 342.71, 333.98]
colors = np.array(colors)
area= [0.78, 0.81, 0.78, 0.81, 0.78, 0.81, 0.787, 0.81, 0.99, 0.999, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99]
area = np.array(area)
area = area*2000

cluster = ['*','.','<','>','o','p','H','D','1','2','o','*','*','o','o','o']

fig,ax = plt.subplots()

for xp, yp, m in zip(x, y, cluster):
    ax.scatter(xp, yp, c=colors, s=area, cmap=plt.cm.jet , marker = m)

plt.show()

python 说 "Color array must be two-dimensional"

当我为每个数据点使用通用标记时

plt.scatter(xp, yp, c=colors, s=area, cmap=plt.cm.jet , marker = 'o')

色谱工作正常,有什么问题吗?

您正在分别绘制每个点作为其自己的散点图。能够为每个点赋予自己的标记确实有意义。但是,这也需要为每个点指定自己的大小和颜色。因此,您还需要遍历 colorsarea 数组的项目。为了使颜色服从指定的颜色图,您还需要标准化。

import matplotlib.pyplot as plt
import numpy as np

y= [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
x= [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]
colors= [286.135, 288.556, 286.135, 288.55, 286.13, 288.55627, 286.13, 288.556, 342.713, 333.98, 342.713, 333.9834, 342.713, 333.9834, 342.71, 333.98]
colors = np.array(colors)
area= [0.78, 0.81, 0.78, 0.81, 0.78, 0.81, 0.787, 0.81, 0.99, 0.999, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99]
area = np.array(area)
area = area*2000

cluster = ['*','.','<','>','o','p','H','D','1','2','o','*','*','o','o','o']

fig,ax = plt.subplots()

norm=plt.Normalize(colors.min(), colors.max())
for xp, yp, m,a,c in zip(x, y, cluster, area, colors):
    sc = ax.scatter(xp, yp, c=c, s=a, cmap=plt.cm.jet , marker = m, norm=norm)

plt.colorbar(sc)
plt.show()