Home > Software engineering >  Creating a 2D color gradient based on RGB values in matplotlib
Creating a 2D color gradient based on RGB values in matplotlib

Time:03-05

I would like to create a simple 2D square figure containing 2 color gradients based on RGB values, such that:

1) the bottom left corner of the square (0, 0) is green [0, 255, 0]
2) the bottom right corner of the square (255, 0) is red [255, 0, 0]
3) the top left corner of the square (0, 255) is blue [0, 0, 255]
4) the top right corner of the square (255, 255) is purple [255, 0, 255]

I think there should be a quick and easy way to do this with numpy and matplotlib, but I'm not seeing it.

CodePudding user response:

Figured it out without numpy, this is what I was looking for (in case anybody is interested):

from __future__ import division
import matplotlib.pyplot as plt

xlist = []
ylist = []
colorlist = []

for i in range(0, 256):
    for j in range(0, 256):
        xlist.append(i)
        ylist.append(j)
        if i > j:
            colorlist.append(((float(i/255), float((255-i)/255), float(j/255))))
        else:
            colorlist.append(((float(i/255), float((255-j)/255), float(j/255))))

fig = plt.scatter(xlist, ylist, c=colorlist, edgecolor='none', marker='s')
plt.axis('off')
plt.show()

enter image description here

CodePudding user response:

import numpy as np

from numpy.random import random

import matplotlib.pyplot as plt

T = random((3,2))
print(T.shape)

plt.imshow(T)

Output:

[Returns random RGB colors]

https://i.stack.imgur.com/MRXy4.png

  • Related