Skip to content Skip to sidebar Skip to footer

Create Legend For Scatter Plot Using The Label Of The Samples In Matplotlib

I am using scatter plot in matplotlib to plot some points. I have two 1D arrays each storing the x and y coordinate of the samples. Also there is another 1D array that stores the l

Solution 1:

You could do it with a colormap. Some examples of how to do it are here.

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
X = [1,2,3,4,5,6,7]
Y = [1,2,3,4,5,6,7]
label = [0,1,4,2,3,1,1]

# Define a colormap with the right number of colors
cmap = plt.cm.get_cmap('jet',max(label)-min(label)+1)

bounds = range(min(label),max(label)+2)
norm = colors.BoundaryNorm(bounds, cmap.N)

plt.scatter(X, Y, c= label, s=50, cmap=cmap, norm=norm)

# Add a colorbar. Move the ticks up by 0.5, so they are centred on the colour.
cb=plt.colorbar(ticks=np.array(label)+0.5)
cb.set_ticklabels(label)

plt.show()

You might need to play around to get the tick labels centred on their colours, but you get the idea.

enter image description here

Post a Comment for "Create Legend For Scatter Plot Using The Label Of The Samples In Matplotlib"