[英]How to associate labels to data in matplotlib color bar and scatter plot
I have currently 2d data X
and a 1d vector y
of color codes per row in X
.我目前有 2d 数据
X
和X
每行的颜色代码的 1d 向量y
。 I am trying to use the function scatter
in matplotlib
to assign a color code point in y
to each row value in X
with the following code using a label:我正在尝试使用
matplotlib
的函数scatter
将y
的颜色代码点分配给X
每一行值,并使用以下代码使用标签:
import matplotlib.pyplot as plt
import numpy as np
classes = 2
zones = (['FEF', 'IT'])
X = np.array([[-1.61160406, 0.06705226],
[-2.34304523, 0.19353161],
[-4.39162911, -0.15401544],
[-1.9107751 , 0.67541723],
[-1.76792646, 0.71884401]])
y= np.array(['c', 'mediumpurple', 'mediumpurple', 'c', 'c'], dtype='<U12')
plt.scatter(X[:, 0], X[:, 1], color=y)
plt.colorbar(ticks=range(classes)).set_ticklabels(zones)
plt.show()
I am getting the following error:我收到以下错误:
TypeError: You must first set_array for mappable
类型错误:您必须先为可映射设置 set_array
Ok, the problem was not in the plt.scatter
but in the plt.colorbar
.好的,问题不在
plt.scatter
而是在plt.colorbar
。 This was not clear from the initial question because you didn't include the second command before.这在最初的问题中并不清楚,因为您之前没有包含第二个命令。 It took some comments to find the problem.
花了一些评论才发现问题。
The problem was that you were not creating any color map but was trying to show it without having any mappable numerical values to your color map.问题是您没有创建任何颜色图,而是试图在没有任何可映射数值到您的颜色图的情况下显示它。 The solution below does the following things:
下面的解决方案执行以下操作:
np.unique
.np.unique
找到颜色数组中的唯一颜色。ListedColormap
from your defined colors.ListedColormap
从您定义的颜色创建自定义颜色映射。 This was inspired by the solution provided here . Here is a complete solution:这是一个完整的解决方案:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
classes = 2
zones = (['FEF', 'IT'])
X = np.array([[-1.61160406, 0.06705226],
[-2.34304523, 0.19353161],
[-4.39162911, -0.15401544],
[-1.9107751 , 0.67541723],
[-1.76792646, 0.71884401]])
y = np.array(['c', 'mediumpurple', 'mediumpurple', 'c', 'c'], dtype='<U12')
cmap = ListedColormap(np.unique(y))
# print (np.unique(y))
# ['c' 'mediumpurple']
# Mapping the colors to numbers
dics = {k: v for v, k in enumerate(sorted(set(y)))}
y_mapped = [dics[x] for x in y]
# print (y_mapped)
# [0, 1, 1, 0, 0]
plt.scatter(X[:, 0], X[:, 1], c=y_mapped, cmap=cmap)
plt.colorbar(ticks=range(classes)).set_ticklabels(zones)
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.