前言
遥感影像分类图一般为特定数值对应一类地物,用python绘制时,主要在颜色的映射和对应的图例生成。
plt.matplotlib.colors.listedcolormap支持自定义颜色。matplotlib.patches mpatches对象可以生成一个矩形对象,控制其颜色和地物类型的颜色对应就可以生成地物分类的图例了。具体用法可以自行google和百度。下面给出一个模拟地物分类数据的可视化例子。
代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
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('') |
效果图:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/tk20190411/article/details/115799071