How to create a scatter plot with several colors in matplotlib ?

April 05, 2019    /    Viewed: 111771    /    Comments: 0    /    Edit


Examples of how to create a scatter plot with several colors in matplotlib:

Combining two scatter plots with different colors

To change the color of a scatter point in matplotlib, there is the option "c" in the function scatter. First simple example that combine two scatter plots with different colors:

How to create a scatter plot with several colors in matplotlib ?

import matplotlib.pyplot as plt

x = [1,2,3,4]
y = [4,1,3,6]

plt.scatter(x, y, c='coral')

x = [5,6,7,8]
y = [1,3,5,2]

plt.scatter(x, y, c='lightblue')

plt.title('Nuage de points avec Matplotlib')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig('ScatterPlot_05.png')
plt.show()

Scatter plots with several colors using a colormap

Example of how to associate a color to a given number or class (source):

How to create a scatter plot with several colors in matplotlib ?

import matplotlib.pyplot as plt
import numpy as np

a = np.array([[ 1, 2, 3, 4, 5, 6, 7, 8 ],
              [ 1, 4, 8, 14, 12, 7, 3, 2 ]])

categories = np.array([0, 2, 1, 1, 1, 2, 0, 0])

colormap = np.array(['r', 'g', 'b'])

plt.scatter(a[0], a[1], s=100, c=colormap[categories])

plt.savefig('ScatterClassPlot.png')
plt.show()

Scatter plot with custom colors

Another example

How to create a scatter plot with several colors in matplotlib ?

import matplotlib.pyplot as plt
import numpy as np

a = np.array([[ 1, 1.5, 2.5, 3, 3.5, 6.5, 5, 6, 7, 8, 7.5 ],
              [ 8, 11, 10, 8, 12, 4.3, 4, 7, 2, 5, 7.5 ]])

categories = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]) # Supervised
#categories = np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) # Unsupervised

color1=(0.69411766529083252, 0.3490196168422699, 0.15686275064945221, 1.0)
color2=(0.65098041296005249, 0.80784314870834351, 0.89019608497619629, 1.0)

colormap = np.array([color1,color2])

plt.scatter(a[0], a[1], s=500, c=colormap[categories])

plt.scatter(2, 6, s=500, c='k')
plt.text(2.4, 5.7, '?', fontsize=16)
plt.text(1.4, 8, 'Label 1', fontsize=16)
plt.text(6.5, 5.8, 'Label 2', fontsize=16)
plt.title('Supervised Learning')

plt.savefig('ScatterClassPlot.png')
plt.show()

References

Links Site
matplotlib.pyplot.scatter Matplotlib doc
Nuage de points avec Matplotlib science-emergence
Using multiple colors in matplotlib plot stackoverflow


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!