plt.matplotlib.colors.ListedColormap支持自定义颜色。matplotlib.patches mpatches对象可以生成一个矩形对象,控制其颜色和地物类型的颜色对应就可以生成地物分类的图例了。具体用法可以自行Google和百度。下面给出一个模拟地物分类数据的可视化例子。
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
data = np.random.randint(0, 3, size=(100,100))
colors = dict((
(0, (0, 255, 0, 255)), # 前三位RGB,255代表256色
(1, (0, 0, 255, 255)),
(2, (255, 255, 0, 255)),
))
# 转换为0-1
for k in colors:
v = colors[k]
_v = [_v / 255.0 for _v in v]
colors[k] = _v
index_colors = [colors[key] if key in colors else
(255, 255, 255, 0) for key in range(0, len(colors))]
cmap = plt.matplotlib.colors.ListedColormap(index_colors, 'Classification', len(index_colors)) # n等于颜色表长度,否则被截断或被重复
# cmap = plt.matplotlib.colors.ListedColormap(['gray', 'orange', 'k'], 'Classification')
plt.rcParams['font.family'] = 'Arial'
plt.rcParams['font.size'] = 10
plt.rcParams['font.weight'] = 'bold'
fig, ax = plt.subplots(figsize=(4,3.5), dpi=300)
ax.imshow(data, cmap=cmap, interpolation='none')
# 绘制矩形的补丁, 用来生成图例,fig.add_artist()才会在图中显示出来
import matplotlib.patches as mpatches
rectangles = [mpatches.Rectangle((0, 0,), 1, 1, facecolor=index_colors[i])
for i in range(len(index_colors))]
labels = ['forest',
'water',
'urban']
ax.legend(rectangles, labels,
bbox_to_anchor=(1.4, 0.25), fancybox=True, frameon=False,)
# 取消刻度和标签显示
ax.tick_params(which='major', bottom=0, left=0)
ax.set_xticklabels('')
ax.set_yticklabels('')