matplotlib pcolormesh离散颜色

时间:2014-10-25 06:05:29

标签: python matplotlib colors colormap

from matplotlib.pyplot import *
import numpy as np

x      = np.linspace( 1., 4., 2 )
y      = np.linspace( 1., 2., 2 )
x,y    = np.meshgrid( x, y )
z      = np.array( [ [ 0.5, 1.5 ], [ 2.5, 3.5 ] ] )
cmap   = matplotlib.colors.ListedColormap( [ 'r', 'y', 'g', 'b' ] )
bounds = [ 0.,  1.,  2.,  3.,  4. ]
ticks  = [ 0.5, 1.5, 2.5, 3.5 ]
norm   = matplotlib.colors.BoundaryNorm( bounds, cmap.N )
fig    = figure( figsize = ( 20, 10 ) )
ax     = fig.add_subplot( 111 )
ax.pcolormesh( x, y, z, cmap = cmap, norm = norm )
ax.axis( [ x.min(), x.max(), y.min(), y.max() ] )
ax.set_xlabel( 'x' )
ax.set_ylabel( 'y' )
m      = cm.ScalarMappable( cmap = cmap )
m.set_array( z )
cbar   = fig.colorbar( m, norm = norm, boundaries = bounds, aspect = 20, ticks = ticks )
cbar.set_ticklabels( [ 'A', 'B', 'C', 'D' ] )
show()

根据 z 的值,我想要一个4字段的colormesh。由于第一个z - 条目0.5位于区间[0.,1。]中,我希望它为 red ,第二个 {{1} 等等。

色条显示我想要的完美,但情节本身是错误的。

也许我对BoundaryNorm有些不对劲?

1 个答案:

答案 0 :(得分:0)

这应该这样做:

from matplotlib.pyplot import *
import numpy as np

x = np.linspace(1.,4.,3)
y = np.linspace(1.,2.,3)
x,y = np.meshgrid(x,y)
z = np.array([[0.5,1.5],[2.5,3.5]])
cmap = matplotlib.colors.ListedColormap(['r', 'y', 'g', 'b'])
bounds = [0.,1.,2.,3.,4.]
ticks = [0.5,1.5,2.5,3.5]
norm = matplotlib.colors.BoundaryNorm(bounds, cmap.N)
fig = figure(figsize = (20,10))
ax = fig.add_subplot(111)
p = ax.pcolormesh(x,y,z, cmap=cmap, norm = norm, vmin=0, vmax=4)
ax.axis([x.min(),x.max(),y.min(),y.max()])
ax.set_xlabel('x')
ax.set_ylabel('y')
cbar = fig.colorbar(p, norm = norm, boundaries = bounds, 
           aspect = 20, ticks = ticks)
cbar.set_ticklabels(['A','B','C','D'])
show()

x和y定义正方形的角。所以它们应该是3x3。你应该定义pcolormesh的vmin / vmax参数。

我还注意到,如果使用vmin / vmax(至少在这个简单的例子中),你不需要明确指定边界和规范,这会使整个事情变得更短:

from matplotlib.pyplot import *
import numpy as np

x = np.linspace(1.,4.,3)
y = np.linspace(1.,2.,3)
x,y = np.meshgrid(x,y)
z = np.array([[0.5,1.5],[2.5,3.5]])
cmap = matplotlib.colors.ListedColormap(['r', 'y', 'g', 'b'])
ticks = [0.5,1.5,2.5,3.5]
fig = figure(figsize = (20,10))
ax = fig.add_subplot(111)
p = ax.pcolormesh(x,y,z, cmap=cmap, vmin=0, vmax=4)
ax.axis([x.min(),x.max(),y.min(),y.max()])
ax.set_xlabel('x')
ax.set_ylabel('y')
cbar = fig.colorbar(p, aspect = 20, ticks=ticks)
cbar.set_ticklabels(['A','B','C','D'])
show()