利用matplotlib.pyplot工具生成颜色数组
用途
利用循环语句生成图表时,有时希望自定义每组数据在图表上颜色
如果多组数据在同一图表上生成图形,其实matplotlib.pyplot会自动给每组数据分配不同的颜色
例如:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,10,1000,endpoint=False)
ys = [0, 4, 5, 3, 8, 9, 1, 7, 6, 2]
print(ys)
plt.figure(figsize=(10,8))
ax = plt.gca()
for i in range(10):
plt.scatter(x=x,y=np.full(1000,ys[i]),s=1,label=i)
plt.legend(fontsize=12)
plt.show()
对应的图像(标签值对应的是直线插入的顺序)如下:
颜色很美,但如果你想找出第一行插入的行在哪里,第二行插入的行在哪里,其实并不直观,甚至很难找到。
[En]
The color is beautiful, but if you want to find out where the first inserted line is and where the second inserted line is, it is actually not intuitive or even difficult to find.
因此,有时我们想要一组更规则的颜色来区分,这意味着我们需要指定每条数据的颜色。
[En]
So, sometimes we want a more regular set of colors to distinguish, which means we need to specify the color of each piece of data.
比如我们按数据插入先后顺序,每条线按从红到蓝显示,就像下图这样,通过颜色的递进关系一眼就能看出y=0的这条直线是第一条插入的,y=4的这条是第二条插入的
方法
要实现上面的效果,首先就是生成颜色数组
-
手动写一个数组列表的方法就不具体介绍了,自己搜一下有哪些颜色就行
-
想要介绍的是从一个颜色渐进的图谱中取颜色
常见的地图集颜色有,您可以搜索每种颜色的对应名称,也可以自己定义渐变颜色:[En]
Common atlas colors are, you can search for the corresponding names of each color, and you can define a gradient color by yourself:
get_cmap
然后我们要用到的一个主要函数是 matplotlib.pyplot.get_cmap(name=None, lut=None)
简单来说, get_cmap()
有两个参数:
name
:颜色图谱,可以是字符串,也可以是colormap实例
lut
:要得到的颜色个数,一个整数
colors = plt.get_cmap('RdBu',10)
colors([0,1,2,3,4,5,6,7,8,9,10,11])
得到以下结果,可以看出这是个narray二维数组(只传入一个整数且不用列表,则返回一个python数组,plt绘图时需要二维数组的颜色),且大于9的数值都是一样的颜色了(这与我们设置了分为10段有关)
array([[0.40392157, 0. , 0.12156863, 1. ],
[0.71372549, 0.1254902 , 0.18344227, 1. ],
[0.86535948, 0.43660131, 0.34814815, 1. ],
[0.96862745, 0.71764706, 0.6 , 1. ],
[0.98169935, 0.90762527, 0.86405229, 1. ],
[0.88583878, 0.92941176, 0.95337691, 1. ],
[0.65490196, 0.81437908, 0.89411765, 1. ],
[0.33159041, 0.62004357, 0.78823529, 1. ],
[0.14422658, 0.41960784, 0.68453159, 1. ],
[0.01960784, 0.18823529, 0.38039216, 1. ],
[0.01960784, 0.18823529, 0.38039216, 1. ],
[0.01960784, 0.18823529, 0.38039216, 1. ]])
上面那幅红-蓝渐变色的图表是根据下方代码得到的
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,10,1000,endpoint=False)
ys = [0, 4, 5, 3, 8, 9, 1, 7, 6, 2]
print(ys)
plt.figure(figsize=(10,8))
ax = plt.gca()
for i in range(10):
plt.scatter(x=x,y=np.full(1000,ys[i]),s=1,label=i,c=plt.get_cmap('RdBu',10)([i]))
plt.legend(fontsize=12)
plt.show()
生成渐变颜色数组的方法
def get_colors(name, lut):
"""
params:
- name:颜色图谱,可以是字符串,也可以是colormap实例
- lut:要得到的颜色个数,一个整数
"""
return plt.get_cmap(name, lut)([i for i in range(lut)])
效果就是这样
Original: https://blog.csdn.net/weixin_43412231/article/details/117335904
Author: weixin_43412231
Title: python生成颜色数组

基于Matlab的SLIC超像素分割算法分析

关于python环境中hdf5报错问题的几种解决办法(亲测)

点钞机语音怎么打开_原来电脑自带有文字转语音方法,只需一个键,再也不担心要配音了…

Mask2Former

抖音小视频背景歌名识别的学习

Ubuntu安装TensorFlow详细过程

调用opensmile编译的DLL动态库API进行声音特征提取

目标检测–边框回归损失函数SIoU原理详解及代码实现

一、音频基础知识 – 专业词汇

【深度学习理论】(6) 循环神经网络 RNN

tensorflow在使用过程中遇到的各种小问题

实战Transformer在NLP和医学图像分割领域的应用

Opencv基础 (二):使用OpenCV读取和写入视频

tf.cast()用法总结
