python – 来自tab10的matplotlib泛型colormap
这个问题与SO(
matplotlib-change-colormap-tab20-to-have-three-colors)的这个问题有关
我想以一种方式调整tab10色彩图,我可以按照我想要的步骤更改每种颜色的alpha级别.下面是一个示例(9种颜色,3个alpha级别),不会产生预期的输出.此外,它不够通用(因为if elif staements). 任何想法我怎么能这样做? 在这个例子中,我有3个组,有3个子组: import pandas as pd from matplotlib import pyplot as plt import numpy as np n_feature = 3 sub_feature = 3 col = [] for index in range(n_feature*sub_feature): # loop over colors and change the last entry in descending order 3 times col.append(list(plt.cm.tab10(index))) i = 0 for item in col: # loop over colors and change the last entry in descending order 3 times if i == 0: item[-1] = 0.9 i+=1 elif i == 1: item[-1] = 0.7 i+=1 elif i == 2: item[-1] = 0.5 i = 0 gr = df.groupby(['a','a1']) for index,item in enumerate(gr): name,val = item y = val.iloc[0,2:].values x = np.arange(len(y)) plt.plot(x,y,'.-',color=col[index]) plt.show() 这是数据: {‘a’:{0:’A’,1:’A’,2:’A’,3:’B’,4:’B’,5:’B’,6:’C’,7: ‘C’,8:’C’}, 解决方法
您可以使用HSV系统获得相同色调的不同饱和度和发光颜色.假设您最多有10个类别,则tab10地图可用于获取一定数量的基色.从那些你可以为子类别选择几个较浅的色调.
以下是一个函数categorical_cmap,它将类别数(nc)和子类别数(nsc)作为输入,并返回具有不同颜色的nc * nsc的颜色映射,其中每个类别都有相同色调的nsc颜色. import numpy as np import matplotlib.pyplot as plt import matplotlib.colors def categorical_cmap(nc,nsc,cmap="tab10",continuous=False): if nc > plt.get_cmap(cmap).N: raise ValueError("Too many categories for colormap.") if continuous: ccolors = plt.get_cmap(cmap)(np.linspace(0,1,nc)) else: ccolors = plt.get_cmap(cmap)(np.arange(nc,dtype=int)) cols = np.zeros((nc*nsc,3)) for i,c in enumerate(ccolors): chsv = matplotlib.colors.rgb_to_hsv(c[:3]) arhsv = np.tile(chsv,nsc).reshape(nsc,3) arhsv[:,1] = np.linspace(chsv[1],0.25,nsc) arhsv[:,2] = np.linspace(chsv[2],nsc) rgb = matplotlib.colors.hsv_to_rgb(arhsv) cols[i*nsc:(i+1)*nsc,:] = rgb cmap = matplotlib.colors.ListedColormap(cols) return cmap c1 = categorical_cmap(4,3,cmap="tab10") plt.scatter(np.arange(4*3),np.ones(4*3)+1,c=np.arange(4*3),s=180,cmap=c1) c2 = categorical_cmap(2,5,cmap="tab10") plt.scatter(np.arange(10),np.ones(10),c=np.arange(10),cmap=c2) c3 = categorical_cmap(5,4,cmap="tab10") plt.scatter(np.arange(20),np.ones(20)-1,c=np.arange(20),cmap=c3) plt.margins(y=0.3) plt.xticks([]) plt.yticks([0,2],["(5,4)","(2,5)","(4,3)"]) plt.show() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |