散点图颜色栏-Matplotlib [英] Scatter plot colorbar - Matplotlib
问题描述
我正在尝试显示散点图的颜色条,但我一直在收到错误消息:
TypeError:您必须首先为可映射设置set_array
这就是我要绘制的内容:
# 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)
如果我在行plt.colorbar(pts)
上添加注释,则可以正确绘制图形,但是我也想绘制颜色条.
谢谢.
您要传递特定的rgb值,因此matplotlib无法构造颜色图,因为它不知道其与原始数据的关系. /p>
让scatter
代替您将值映射为RGB颜色.
代替:
# 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)
做:
pts = plt.scatter(x_data, y_data, marker='s', c=data[x_data, y_data])
(只需将您最初传递给plt.cm.jet
的内容传递到c
.)
然后,您将能够正常构建颜色图.特定的错误是告诉您颜色是手动设置的,而不是通过set_array
(用于处理将数据值数组映射到RGB)设置的.
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.
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).
这篇关于散点图颜色栏-Matplotlib的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!