Comment définir une échelle de couleur discrète pour imshow sous matplotlib ?


Avec matplotlib il est possible de définir une échelle de couleur discrète pour imshow, illustration:

Définir une échelle de couleur discrète pour imshow sous matplotlib (1/3)

from matplotlib import mpl,pyplot
import numpy as np

Data = np.random.rand(100,100)*100

cmap = mpl.colors.ListedColormap(['blue','black','red'])
bounds=[0,25,75,100]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

img = pyplot.imshow(Data,interpolation='nearest', cmap = cmap,norm=norm)

pyplot.colorbar(img,cmap=cmap, norm=norm,boundaries=bounds,ticks=[0,25,75,100])

pyplot.savefig("DiscreteColorbarImshow01.png")
pyplot.show()

Possible de partir d'une colorbar déjà existantes (voir) sous matplotlib:

Définir une échelle de couleur discrète pour imshow sous matplotlib (2/3)

from matplotlib import mpl,pyplot
import numpy as np
import matplotlib.cm as cm

Data = np.random.rand(100,100)*100

cmap = cm.gist_earth

bounds=[0,25,75,100]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

img = pyplot.imshow(Data,interpolation='nearest', cmap = cmap,norm=norm)

pyplot.colorbar(img,cmap=cmap, norm=norm,boundaries=bounds,ticks=[0,25,75,100])

pyplot.savefig("DiscreteColorbarImshow02.png")
pyplot.show()

Un exemple plus complexe qui nécessite les fichiers:

  • [attachment:514]
  • [attachment:515]

pour pouvoir exécuter le code ci-dessous:

Définir une échelle de couleur discrète pour imshow sous matplotlib (3/3)

#!/usr/bin/env python

'''
Copyright (c) 2013 Marchant Benjamin
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''

from mpl_toolkits.basemap import Basemap, cm
from datetime import datetime
from pylab import *
import numpy as np
import matplotlib.pyplot as plt


import my_sivo

Month = 'November'
Year = '2012'
Collection = 'C6'
CSR_Flag = '0'

#----- Get Data -----#

Data = np.loadtxt("GlobalMap_PAF.txt")
print Data.shape

#----- Define PAF -----#

DataR = Data.reshape((180,360,6))

PAF_matrix = np.zeros((180,360))

#for i in range(100):
#    print DataR[8,i,0]

for i in range(180):
    for j in range(360):
        total = DataR[i,j,0]+DataR[i,j,1]+DataR[i,j,2]+DataR[i,j,3]+DataR[i,j,4]+DataR[i,j,5]
        if total > 0:
            PAF_matrix[i,j] = (DataR[i,j,0]+DataR[i,j,4])/total
        else:
            PAF_matrix[i,j] = 0


PAF_matrix = np.zeros((180/10,360/10))
PAF_Num_matrix = np.zeros((180/10,360/10))
PAF_Den_matrix = np.zeros((180/10,360/10))

for i in range(180):
    for j in range(360):
        i_cr = int( i / 10 )
        j_cr = int( j / 10 )
        total = DataR[i,j,0]+DataR[i,j,1]+DataR[i,j,2]+DataR[i,j,3]+DataR[i,j,4]+DataR[i,j,5]
        PAF_Num_matrix[i_cr,j_cr] = PAF_Num_matrix[i_cr,j_cr] + DataR[i,j,0] + DataR[i,j,4]
        PAF_Den_matrix[i_cr,j_cr] = PAF_Den_matrix[i_cr,j_cr] + total

for i in range(180/10):
    for j in range(360/10): 
        if PAF_Den_matrix[i,j] > 0:
            PAF_matrix[i,j] = PAF_Num_matrix[i,j] / PAF_Den_matrix[i,j]
        else:
            PAF_matrix[i,j] = 0



#----- Plot Grid Observation Frequency -----#

fig = plt.figure()
m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90, llcrnrlon=-180,urcrnrlon=180,resolution='c')
m.drawcoastlines()
m.drawlsmask(land_color='white',ocean_color='white',lakes=True)
m.drawparallels(np.arange(-90.,90.,30.))
m.drawmeridians(np.arange(-180.,180.,30.))
m.drawmapboundary(fill_color='aqua')
plt.title("MODIS "+Collection+" - CALIOP ($10^{\circ}$ by $10^{\circ}$ grid) PAF \n " + Month + ' ' + Year)
colors = [(0.33,0.33,0.33)] + [(my_sivo.nasa(i)) for i in xrange(1,256)]
new_map = matplotlib.colors.LinearSegmentedColormap.from_list('new_map', colors, N=256)
bounds=[0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0]
norm = matplotlib.colors.BoundaryNorm(bounds, new_map.N)
img = m.imshow(PAF_matrix, cmap=new_map, interpolation='nearest', vmin=0, vmax=1.0, norm=norm )
cb = m.colorbar(img,"bottom", size="5%", pad='4%', boundaries=bounds, ticks=[0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0])
plt.savefig("CloudFraction_liq_"+Collection+"_CSR"+CSR_Flag+".png", dpi=100 )
#plt.show()

Recherches associées

Image

of