Search code examples
pythonnumpycolorsscatter-plotalpha

different colours and alpha values based on array values


I have arrays similar to the following:

a_1 = [2]
v_1 = [6,7,8,9]
plt.scatter(np.tile(a_1[0],4), v_1, color='r', alpha=0.5)

Here, I would like to have a separate alpha value to each data points with the highest value in the v_1 array getting the alpha value closer to 1 and the lowest getting the smallest alpha value.

I have few more arrays similar to above with different lengths of v_* array like:

a_2 = [5]
v_2 = [3,0.2,1,5,7,9] 
plt.scatter(np.tile(a_2[0],6), v_2, color='b', alpha=0.4)

Note: np.tile(a_*[0],length_of_v value varies w.r.t to the length of the v_x value.

Here, I would like to allocate different colours for different values of a_* and for each colour, different alpha values needs to be allocated based on the v_* arrays values. ( highest value getting alpha closer to 1 and least getting alpha value closer to 0 and the remains in better following the order)

Could someone please specify how to implement this in a loop having different a_* and v_* arrays ?


Solution

  • Let's try computing alpha and pass to scatter:

    def get_color(v, 
                  offset=0.3,         # minimal alpha, we don't want transparent points
                  base_color=(1,0,0)  # (1,0,0) for red, (0,1,0) for green, etc
                 ):
        v = np.array(v)
        scaled = (v-v.min())/np.ptp(v)
        scaled = offset + (1-offset)*scaled
        return [base_color+(s,) for s in scaled]
    
    plt.scatter(np.tile(a_1[0],4), v_1, c=get_color(v_1))
    

    Output:

    enter image description here