matplotlib draws color scale gradient color bar

This example uses the matplotlib library to draw a gradient map of the three primary colors of red, green, and blue. The basic principle is to use long and narrow solid color rectangles to represent each color level, and draw them in a picture, the effect is as shown in the figure.

renderings

1 Implementation idea

Note: In matplotlib, the range of color triplet elements is 0~1.0 instead of 0~255.

Red bar RGB range: (0, 0, 0)~(1.0, 0, 0)

Green bar RGB range: (0, 0, 0)~(0, 1.0, 0)

Blue bar RGB range: (0, 0, 0)~(0, 0, 1.0)

2 codes

import matplotlib.pyplot as plt

a = [i for i in range(256)] #色阶数(256),越大越精细
rgb_mask = [0, 0, 1]    #更改0与1的顺序可以调换色条颜色

fig = plt.figure()
ax = fig.add_subplot() #创建子图
ax.set(xlim=(0, 300), ylim=(0, 13)) #坐标范围

for c in range(3):
    for i in range(256):
        rect = plt.Rectangle(xy=(i, 3.5*c+4),
                             width=1,
                             height=1,
                             color=(a[i]/255*rgb_mask[c%3], a[i]/255*rgb_mask[(c+1)%3], a[i]/255*rgb_mask[(c+2)%3])
                             )
        ax.add_patch(rect)

plt.show()

 

Guess you like

Origin blog.csdn.net/diqiudq/article/details/126296221