Greenfire
Greenfire

Reputation: 103

Scatter plot colors corresponding to a value

In all the colormap posts I have not found this answer, or maybe did not understand it.

I want to make a scatter plot with colors.

I have a list B:

[1.29,
 1.27,
 1.46,
 0.91,
 0.56,
 0.99,
 1.00,
 0.37,
 1.24,
 1.23]

I will just use a stupid example, if you do:

import matplotlib.pyplot as plt
from matplotlib import cm
from math import sin

x=range(10)
y=[sin(i) for i in x]
colors=np.linspace(0,1,10)

plt.scatter(x,y,c=colors,cmap=cm.jet)

You get points with different colors, nice. enter image description here

BUT ! I do not want to only get nicely colored points ! I want the points to be colored according to the "intensity" of the values in B.

Here is my stupid attempt:

import matplotlib.pyplot as plt
from matplotlib import cm
from math import sin

x=range(10)
y=[sin(i) for i in x]
#colors=np.linspace(0,1,10)
B=[1.29,1.27,1.46,0.91,0.56,0.99,1.00,0.37,1.24,1.23]

plt.scatter(x,y,c=B,cmap=cm.jet)

You get points colored according to the intensity of the values in B, very nice: enter image description here

BUT !! I would like to change the "scale" of colors to have deep blue at 0 and deep red at 2. In which case the third point (associated with B[2]=1.46) should be orange and not deep red ! How should I do this?

Upvotes: 5

Views: 6767

Answers (1)

Ed Smith
Ed Smith

Reputation: 13196

You need to set the minimum and maximum colour manually using vmin and vmax arguments. For your case, this is,

import matplotlib.pyplot as plt
from matplotlib import cm
from math import sin

x=range(10)
y=[sin(i) for i in x]
#colors=np.linspace(0,1,10)
B=[1.29,1.27,1.46,0.91,0.56,0.99,1.00,0.37,1.24,1.23]

cs = plt.scatter(x,y,c=B,cmap=cm.jet,vmin=0.,vmax=2.)
plt.colorbar(cs)
plt.show()

Upvotes: 7

Related Questions