I have a simulation set up for traffic flow and i require a visualisation of the system for which ive used a scatter plot. I am looking for a way to give each element in my array a different color but one that is constant as my program loops
2 Answers
You can set the colour of scatter plot points using c=... in the call to scatter:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 11, 12, 11, 9]
z = [2, 4, 4, 1, 1]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(x, y, c=z, linewidth=0)
plt.show()
To give each point its own colour simply use range(len(x)) for the colours:
x = [1, 2, 3, 4, 5]
y = [10, 11, 12, 11, 9]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(x, y, c=range(len(x)), linewidth=0)
plt.show()
Comments
Looking at the plt.scatter documentation, one finds that the c argument can be used for setting the color of the scatter points.
c : color, sequence, or sequence of color, optional, default: ‘b’
c can be a single color format string, or a sequence of color specifications
of length N, or a sequence of N numbers to be mapped to colors using
the cmap and norm specified via kwargs (see below).
So, in order to obtain a constant color for each scatter point, there are two options:
Specify an absolute color
plt.scatter(x,y, c=["blue", "red", "green"])
Specify a value to be colormapped according to a normalization
plt.scatter(x,y, c=[3.4, 5.6, 7.9, 1.0], cmap="jet", vmin=0, vmax=10)
or using a Normalize instance
norm = matplotlib.colors.Normalize(vmin=0, vmax=10)
plt.scatter(x,y, c=[3.4, 5.6, 7.9, 1.0], cmap="jet", norm=norm)
Without the normalization, the colors from the colormap would be distributed according the the minimum and maximum value in the array that is given to c.
