Customizing colors in matplotlib - heatmap
如何在heatmap中指定颜色。在本例中,数据是4个值中唯一的一个
1 2 3 4 5 6 7 8 9 | Index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee'] Cols = ['A', 'B', 'C', 'D'] data= [[ 0, 3, 1, 1],[ 0, 1, 1, 1],[ 0, 1, 2, 1],[ 0, 2, 1, 2],[ 0, 1, 1, 1]] print data df = pd.DataFrame(data, index=Index, columns=Cols) heatmap = plt.pcolor(np.array(data)) plt.colorbar(heatmap) plt.show() |
我如何用一种表示的方式来指定那些颜色颜色=0:'绿色',1:'红色',2:'黑色',3:'黄色'
创建自定义颜色映射并将刻度设置为整数
1 2 3 4 5 6 | from matplotlib import colors cmap = colors.ListedColormap(['green','red','black','yellow']) bounds=[-0.5, 0.5, 1.5, 2.5, 3.5] norm = colors.BoundaryNorm(bounds, cmap.N) heatmap = plt.pcolor(np.array(data), cmap=cmap, norm=norm) plt.colorbar(heatmap, ticks=[0, 1, 2, 3]) |
这就是你想要的吗?注意,您的
我修改了这个代码,显示了9个节点的3个红色/黄色/绿色状态
1 2 3 4 5 6 7 8 9 10 11 | import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap colors = [(1, 0, 0), (1, 1, 0), (0, 1, 0)] # Red, yellow, green n_bins = [3] # Discretizes the interpolation into bins cmap_name = 'my_list' cm = LinearSegmentedColormap.from_list(cmap_name, colors, N=3) threshold = 3 # max value data = [[1, 1, 2], [1, 1, 3], [1, 1, 2]] img = plt.imshow(data, interpolation='nearest', vmax=threshold, cmap=cm) plt.show() |