使用matplotlib在散点图中显示颜色问题

时间:2017-09-15 20:02:36

标签: python matplotlib scatter-plot

这很好用

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说“颜色数组必须是二维的”

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

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

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

1 个答案:

答案 0 :(得分:0)

您将每个点分别绘制为自己的散点图。能够为每个点提供自己的标记确实是有意义的。但是,这也需要给每个点自己的大小和颜色。因此,您还需要遍历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()

enter image description here