简体   繁体   中英

color issue in scatter plot with matplotlib

this works fine

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

but when I try to add color spectrum:

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 says "Color array must be two-dimensional"

when I use universal marker for each data point like

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

color spectrum works fine, what's the problem?

You are drawing each point separately as its own scatter plot. This may indeed make sense to be able to give each point its own marker. However, this also requires to give each points its own size and color. Hence you need to loop over the items of the colors and area arrays as well. In order for the colors to obey to the specified colormap you would also need a normalization.

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM