matplotlib colormap非常强大,比其他软件要更好用 [注1],但是相当难理解。大多数时候,可以使用颜色列表创建 colormap:
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from osgeo import gdal
from numpy import linspace
from numpy import meshgrid
from matplotlib.colors import LinearSegmentedColormap
# 表示在[0, 1] 之间创建6个颜色区间
cmap1 = LinearSegmentedColormap.from_list("my_colormap", ((0, 0, 0), (1, 1, 1)), N=6, gamma=1.0)
map = Basemap(projection='tmerc',
lat_0=0, lon_0=3,
llcrnrlon=1.819757266426611,
llcrnrlat=41.583851612359275,
urcrnrlon=1.841589961763497,
urcrnrlat=41.598674173123)
ds = gdal.Open("../sample_files/dem.tiff")
data = ds.ReadAsArray()
x = linspace(0, map.urcrnrx, data.shape[1])
y = linspace(0, map.urcrnry, data.shape[0])
xx, yy = meshgrid(x, y)
map.contourf(xx, yy, data, (400, 600, 800, 1000, 1200),cmap=cmap1)
plt.show()
1)给定 colormap 名
2)颜色列表。这是 一个列表或序列。每个元素都包含0-1之间的三个值,分别是red,green,blue三种颜色
3) N 是要创建的颜色数。如果N 小于颜色列表的长度,列表将会被截断,如果N大于颜色列表的长度,一些颜色会重复
GDAL 中有名为 gdaldem 工具,可以使用文件中定义的值对栅格进行划分。文件格式是 GRASS r.colors 函数最初使用的格式 [注2]。我喜欢这种格式,因为确实很容易理解,而且很多软件都可以使用。下面给一个使用 basemap 读取并使用这种文件的例子:
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from osgeo import gdal
from numpy import linspace
from numpy import meshgrid
from os.path import exists
from matplotlib.colors import LinearSegmentedColormap
def read_color_table(color_file):
'''
The method for reading the color file.
'''
colors = []
levels = []
if exists(color_file) is False:
raise Exception("Color file " + color_file + " does not exist")
fp = open(color_file, "r")
for line in fp:
if line.find('#') == -1 and line.find('/') == -1:
entry = line.split()
levels.append(eval(entry[0]))
colors.append((int(entry[1])/255.,int(entry[2])/255.,int(entry[3])/255.))
fp.close()
cmap = LinearSegmentedColormap.from_list("my_colormap",colors, N=len(levels), gamma=1.0)
return levels, cmap
levels, cmap = read_color_table("../sample_files/colorfile.clr")
map = Basemap(projection='tmerc',
lat_0=0, lon_0=3,
llcrnrlon=1.819757266426611,
llcrnrlat=41.583851612359275,
urcrnrlon=1.841589961763497,
urcrnrlat=41.598674173123)
ds = gdal.Open("../sample_files/dem.tiff")
data = ds.ReadAsArray()
x = linspace(0, map.urcrnrx, data.shape[1])
y = linspace(0, map.urcrnry, data.shape[0])
xx, yy = meshgrid(x, y)
map.contourf(xx, yy, data, levels, cmap=cmap)
plt.show()
3) 使用 LinearSegmentedColormap.from_list 静态方法创建 colormap
4) 函数返回 levles 和 colormap
传递返回的 levles 给 contourf 函数的 levels 参数。由于部分颜色超出了数据范围,因此有些颜色并没有使用。
没有传递返回的 levels 给 contourf 函数的 levels 参数。contourf 将根据数据进行划分。
注1:http://matplotlib.org/api/colors_api.html#matplotlib.colors.Colormap
注2:http://grass.osgeo.org/grass64/manuals/r.colors.html