I tried the following code, but the matching name is used wrong. How to give a name to the created colour map, please?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
cMap = []
for value, colour in zip([28800, 29000, 29200, 29400, 29600, 29800, 30000],["darkblue", "mediumblue", "royalblue", "cornflowerblue", "dodgerblue", "skyblue", "paleturquoise"]):
cMap.append((value, colour))
customColourMap = LinearSegmentedColormap.from_list("pri_c", cMap)
x=np.arange(9)
y=[9,2,8,4,5,7,6,8,7]
plt.scatter(x,y, c=y,cmap='pri_c')
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with Virdis colormap")
plt.colorbar()
plt.show()
CodePudding user response:
If you are working with matplotlib >= 3.5
then you can register the color map with plt.colormaps.register
.
If you are using an older version, use plt.register_cmap
.
You need to map you color values between 0 and 1 so your code would look something like
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
color_values = np.array([28800, 29000, 29200, 29400, 29600, 29800, 30000])
color_values -= color_values[0]
color_values = color_values / color_values[-1]
color_names = ["darkblue", "mediumblue", "royalblue",
"cornflowerblue", "dodgerblue", "skyblue",
"paleturquoise"]
cMap = list(zip(color_values, color_names))
customColourMap = LinearSegmentedColormap.from_list("pri_c", cMap)
# if mpl >= 3.5
plt.colormaps.register(customColourMap)
# if mpl < 3.5
# plt.register_cmap(cmap=customColourMap)
x=np.arange(9)
y=[9,2,8,4,5,7,6,8,7]
plt.scatter(x,y, c=y,cmap='pri_c')
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with Virdis colormap")
plt.colorbar()
plt.show()