Matplotlib离散颜色条标签未正确放置

时间:2015-01-22 09:26:53

标签: python-2.7 matplotlib colorbar

我只是在matplotlib中绘制图像,但是colorbar中的标签没有正确放置。我在colorbar中放置了12个类,但它只显示了其中的一些。我将感谢你的帮助。

from PIL import Image
from scipy import misc
import scipy
import pylab as pl
import numpy as np
from sklearn import svm
from sklearn import neighbors
import matplotlib.pyplot as plt
import matplotlib as mpl

def plotimage(labels,image,imname):#input - array of labels and image of 1..n classes
cmap = mpl.colors.ListedColormap(['r', 'g', 'b', 'c','k','y','m','w','#FFFF00','#FF8C00','#FF8EFC','#962404'])#only 12 classes at present  
#need to create pallate and labels later out of this def
bounds = [0,1, 2, 3,4, 5,6,7,8,9,10,11,12,13]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
img = plt.imshow(image, cmap=cmap )
cbar = plt.colorbar(img, cmap=cmap)  #norm=norm, boundaries=bounds, ticks=bounds
cbar.ax.set_yticklabels(labels)
plt.gcf().canvas.set_window_title("Classification")
#imsave("expr1_im", image.reshape(image.shape[0]/256,256), cmap=cmap)
#savefig(imname)
plt.title(imname)
plt.show()

b_imgarray = np.loadtxt("PlotData2001_Solar/SVM2001PixelArray.csv", delimiter=',')

labels = ['D','F','A','G','R','I','BS','ABG','W','BG','COAG','BSMIX']

a = np.reshape(b_imgarray, (1500,1500))
c = 'SVmimage'
plotimage(labels,a,c)

错位的条形图例的图像。正如您所看到的,我已经定义了从“D”到“BSMIX”的12个标签,但它显示为ABG。 Misplace label image

3 个答案:

答案 0 :(得分:2)

imshow通常会将cmap的范围限制为图片中显示的值。为了强制imshow使用您的cmap的所有值,请使用vminvmax

img = plt.imshow(image, cmap=cmap, vmin=0, vmax=13)

答案 1 :(得分:1)

为了在离散颜色条字段的中心对齐标签,您必须定义固定数量的刻度(以避免子单位)并使用clim()

例如,如果要在颜色栏中显示N个离散级别:

cbar = plt.colorbar(ticks=range(N))
plt.clim(-0.5, N - 0.5)

这是一个古老的问题,但仍然很难找到正确的答案,而且以上都没有对我有用。

答案 2 :(得分:0)

非常感谢@plosner ......我对它进行了一点调整,并且有效......

def plotimage(labels,image,imname):#input - array of labels and image of 1..n classes
    cmap = mpl.colors.ListedColormap(['r', 'g', 'b', 'c','y','k','#FFFF00','#00FF00','#ADBE34','#FF8C00','w','#FF8EFC','#00FFDD','#673E03','#ADEE12','m','#12ABDE','#22EEAB','#33DDEF'])#only 8 classes at present ,'#FF8EFC','#00FF00','#00FFDD''#962404' '#FF8EFC','#962404'
     #need to create pallate and labels later out of this def
    #cmap = mpl.colors.ListedColormap(['r', 'g', 'b', 'c','m','k','y','w','#7FFF00','#FF8C00','#FFFF00','#FE6D06','#6E6E6E','#04B4AE'])#only 8 classes at present ,'#FF8EFC','#00FF00','#00FFDD''#962404' '#FF8EFC','#962404'
    bounds = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
    norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
    print cmap.N
    img = plt.imshow(image, cmap=cmap , vmin = 1, vmax =20)
    cbar = plt.colorbar(img, cmap=cmap,norm=norm, boundaries=bounds, ticks=bounds)  #norm=norm, boundaries=bounds, ticks=bounds
    cbar.ax.set_yticklabels(labels)
    plt.gcf().canvas.set_window_title("Classification")
    #imsave("expr1_im", image.reshape(image.shape[0]/256,256), cmap=cmap)
    #savefig(imname)
    plt.title(imname)
    plt.show()