python科学绘图-matplotlib库中色带colormap的使用方法和技巧
(一)官方提供的色带
import matplotlib
import matplotlib.pyplot as plt
print("-----------获取所有颜色表colormaps----------")
print(matplotlib.colormaps) # 所有官方色带
rainbow = matplotlib.colormaps["rainbow"]
使用matplotlib.colormaps["色带名"]获取对应色带
这里是引入,后面会讲解具体使用方法和技巧
(二)自定义色带
from matplotlib.colors import LinearSegmentedColormap
colors1 = [(0, '#FF0000'), # 红色
(0.5, '#FFFF00'), # 黄色
(1, '#00FF00')] # 绿色
c1 = LinearSegmentedColormap.from_list('name', colors1)
colors2 = [(0, '#000000'), (1, '#FFFFFF')] # 白色、黑色
c2 = LinearSegmentedColormap.from_list('name', colors2)
如代码中一样c1是一条由“红-黄-绿”渐变的颜色带
c2是一条由黑渐变到白的色带,后边会使用这条色带作图,能够清晰看出使用上的差别
(三)获取单个颜色
# 0<x<1
print(0, ' \t', c2(0)) # 0是最左颜色,1是最右颜色
print(0.5, '\t', c2(0.5))
print(1, ' \t', c2(1))
# 0<x<255
print(200.0, '\t', c2(200.0)) # x/255对应到0-1之间
print(255, '\t', c2(255))
# x<0 || x>255
print(-1, ' \t', c2(-1)) # 低于0,显示0
print(100000, '\t', c2(100000)) # 超过255,显示255
从这里了开始就变得抽象起来了,不过不用担心,看看就懂了
首先要明确的是上边获取的c1和c2虽然叫色带,但这是个方法对象!!!(怎么定义方法对象,class里重写def __call__(): …,与本篇无关)
所有后边加括号使用,填入数字,colormap(参数:int),但是要注意,数字的范围和得到的结果,如代码中一样,参数范围为(0~1)、(1~255)、(其他范围) 获取的颜色结果都不一样的,后边有详细讲解
(四)获取多颜色列表
print("-----------获取多颜色colors-----------")
cs1 = c2([0, 0.5, 1]) # 对于数据在0-1之间的可以直接作为参数
print(cs1)
d = np.arange(3)
print(c2(d)) # 结果并不是想要的包含两头的渐变色
print(c2(d / d.max())) # 技巧:d/d.max(),归一化
colormap(序列参数:Sequence[int]),这样就能获取多个渐变色,如代码中 cs1 = c2([0, 0.5, 1]),得到的结果就是(黑,灰,白),注意不在0~1范围内的,可以使用 list/max(list),把整个列表化为0~1以内
(五)对于线图类型的使用技巧
这是一种类型,特点是一条线只有一种颜色
先初始化(真的怕你不会,或者遇到什么麻烦)
import matplotlib
matplotlib.use("TkAgg")
fig, axs = plt.subplots(2, 2)
plt.subplots_adjust(wspace=0.5, hspace=0.5) # 调整子图间距
定义数据和定义方法,其中使用了彩虹rainbow的官方色带,你可以看到color=colors(index / len(xs)),我是这样把色带列表归一化的
x1 = np.arange(5)
y1 = np.arange(1, 101).reshape(20, 5) # 生成一个20行5列的递增数列
def line(ax: plt.Axes, xs, yss):
colors = matplotlib.colormaps["rainbow"]
for index, ys in enumerate(yss):
ax.plot(xs, ys, linewidth=1, color=colors(index / len(xs)))
line(axs[0, 0], x1, y1)
plt.show()
结果图如下,像彩虹一样的颜色渐变而来
(六)对于柱状图类型的使用技巧
这中类型的图,特点是不同的柱子可以是不同的颜色
你可以看到,其中的色带c一个我直接colormap(list),另一个colormap(list/max(list)),(!!!注意把上一个plt.show()删掉)
x2 = np.arange(-100, 500)
def bar1(ax: plt.Axes, xs, ys):
c = c2(ys)
ax.bar(xs, ys, color=c)
def bar2(ax: plt.Axes, xs, ys):
c = c2(ys / ys.max())
ax.bar(xs, ys, color=c)
bar1(axs[1, 0], x2, x2)
bar2(axs[1, 1], x2, x2)
plt.show()
图如下,然后图一出来你也许就能体会到【(三)获取单个颜色】这一块内容的含义了
你可以看出来
在第一个图中,直接colors = colormap(list),那么低于0的都是纯黑色,0~255是“黑->白”渐变色,超出255,就是纯白色
在第二个图中,colors = colormap(list/max(list)),那么就是从最小值到最大值的黑白渐变色
(七)对于热图类型的使用技巧
这类图又与前两者不同,是每个格子一个颜色,plot.imshow()中参数名不是color,而直接是cmap(即色带color map)
代码如下,可以看到,cmap参数直接给色带,而不是具体颜色(!!!注意把上一个plt.show()删掉)
y2 = [[0, 1, 3, 6],
[2, 4, 7, 10],
[5, 8, 11, 13],
[9, 12, 14, 15]]
def hotmap(ax: plt.Axes, yss):
ax.imshow(yss, cmap=c1)
hotmap(axs[0, 1], y2)
plt.show()
图如下:
这就是matplotlib色带的使用方法和技巧,如果对你有帮助,请帮忙点个👍让更多人看到。
作者:zhan114514