Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - Scatter plot colorbar - Matplotlib

I'm trying to show a color bar of my scatter plot but I'm keep getting the error:

TypeError: You must first set_array for mappable

This is what I'm doing to plot:

# Just plotting the values of data that are nonzero 
x_data = numpy.nonzero(data)[0] # x coordinates
y_data = numpy.nonzero(data)[1] # y coordinates

# Mapping the values to RGBA colors
data = plt.cm.jet(data[x_data, y_data])

pts = plt.scatter(x_data, y_data, marker='s', color=data)

plt.colorbar(pts)

If I comment the line plt.colorbar(pts) I got the plot correctly, but I would like to plot the color bar too.

Thank you in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're passing in specific rgb values, so matplotlib can't construct a colormap, because it doesn't know how it relates to your original data.

Instead of mapping the values to RGB colors, let scatter handle that for you.

Instead of:

# Mapping the values to RGBA colors
data = plt.cm.jet(data[x_data, y_data])

pts = plt.scatter(x_data, y_data, marker='s', color=data)

Do:

pts = plt.scatter(x_data, y_data, marker='s', c=data[x_data, y_data])

(Just pass in to c what you were originally passing into plt.cm.jet.)

Then you'll be able to construct a colormap normally. The specific error is telling you that the colors have been manually set, rather than set through set_array (which handles mapping an array of data values to RGB).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...