Matplotlib color according to class labels
我有两个向量,一个具有值,一个具有类标签,例如1,2,3等。
我想将属于红色的1类,属于蓝色的2类,绿色的3类的所有点绘制成图。我该怎么做?
可以接受的答案可以找到答案,但是如果您想指定应该将哪种类别标签分配给特定的颜色或标签,则可以执行以下操作。我使用色标进行了一些标签体操训练,但制作情节本身却减少了线条。这对于绘制sklearn进行分类的结果非常有用。每个标签都匹配一个(x,y)坐标。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import matplotlib import matplotlib.pyplot as plt import numpy as np x = [4,8,12,16,1,4,9,16] y = [1,4,9,16,4,8,12,3] label = [0,1,2,3,0,1,2,3] colors = ['red','green','blue','purple'] fig = plt.figure(figsize=(8,8)) plt.scatter(x, y, c=label, cmap=matplotlib.colors.ListedColormap(colors)) cb = plt.colorbar() loc = np.arange(0,max(label),max(label)/float(len(colors))) cb.set_ticks(loc) cb.set_ticklabels(colors) |
使用此答案的稍作修改的版本,可以将上述内容概括为N种颜色,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt N = 23 # Number of labels # setup the plot fig, ax = plt.subplots(1,1, figsize=(6,6)) # define the data x = np.random.rand(1000) y = np.random.rand(1000) tag = np.random.randint(0,N,1000) # Tag each point with a corresponding label # define the colormap cmap = plt.cm.jet # extract all colors from the .jet map cmaplist = [cmap(i) for i in range(cmap.N)] # create the new map cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N) # define the bins and normalize bounds = np.linspace(0,N,N+1) norm = mpl.colors.BoundaryNorm(bounds, cmap.N) # make the scatter scat = ax.scatter(x,y,c=tag,s=np.random.randint(100,500,N),cmap=cmap, norm=norm) # create the colorbar cb = plt.colorbar(scat, spacing='proportional',ticks=bounds) cb.set_label('Custom cbar') ax.set_title('Discrete color mappings') plt.show() |
这使:
假设您的数据位于2d数组中,这应该可以工作:
1 2 3 4 5 6 7 8 | import numpy import pylab xy = numpy.zeros((2, 1000)) xy[0] = range(1000) xy[1] = range(1000) colors = [int(i % 23) for i in xy[0]] pylab.scatter(xy[0], xy[1], c=colors) pylab.show() |
您还可以设置
1 | pylab.scatter(xy[0], xy[1], c=colors, cmap=pylab.cm.cool) |
可以找到颜色图列表
这里
一个简单的解决方案是为每个类分配颜色。这样,我们可以控制每种类别的每种颜色。例如:
1 2 3 4 5 | arr1 = [1, 2, 3, 4, 5] arr2 = [2, 3, 3, 4, 4] labl = [0, 1, 1, 0, 0] color= ['red' if l == 0 else 'green' for l in labl] plt.scatter(arr1, arr2, color=color) |