Search code examples
pythonmatplotlibcolor-codes

how to plot region-based color coding python


how to plot the following in python? I have 1000 points in 2d. I need to color-code them based on their position in the 2d space as following moving along x-axis increases the green color moving along y-axis increases red color moving along the y=x line, increases green and red equally

the blue color of all points are equal to each other and zero The points are representing error between two ideas (models). So each point is has two values point = [p_x, p_y]. p_x and p_y range between 0 to 1 like the following:

points = np.random.rand(1000, 2)
so each point p = [p_x, p_y]

as an example, the following code makes a scatter plot that the color of points depends on the y location.

# Generate data...
x = np.random.random(10)
y = np.random.random(10)

# Plot...
plt.scatter(x, y, c=y, s=100)

plt.show()

How I can make the color of each point to be based on 2d location in the space, to be depend on both p_x and p_y so that points with higher p_x are greener and points with higher p_y are reder


Solution

  • Just calculate an RGB value based on your points array and use matplotlib.pyplot.scatter with the color parameter:

    import numpy as np
    import matplotlib.pyplot as plt 
    points = np.random.rand(1000, 2)*180
    
    # calculate Red, Green, Blue channels from 0 to 1 based on min/max of points:
    R = (points[:,0] - points[:,0].min())/(points[:,0].max()-points[:,0].min())
    G = (points[:,1] - points[:,1].min())/(points[:,1].max()-points[:,1].min())
    B=np.zeros(R.shape)
    
    # stack those RGB channels into a N x 3 array:
    clrs=np.column_stack((R,G,B)) 
    
    plt.scatter(points[:,0],points[:,1],color=clrs)
    plt.show()
    

    Results in

    point color by position

    EDIT: oops, look like I flipped the directions of the R and G variation you wanted, but this should be enough to get you going.