chevron_left
Graphs Cookbook
Drawing a bar chartDrawing a box plotDrawing a functionDrawing a histogramDrawing a horizontal lineDrawing a line plotDrawing a normal curveDrawing a scatterplotDrawing a single pointDrawing a stacked bar chartDrawing a vertical lineDrawing arrowsDrawing circlesDrawing empty circlesDrawing error barsDrawing horizontal bar plotsDrawing multiple histograms in one plotNormalizing a histogramPlotting scatter plot with category
0
0
0
new
Plotting scatter plot with category in Matplotlib
Programming
chevron_rightPython
chevron_rightMatplotlib
chevron_rightCookbooks
chevron_rightGraphs Cookbook
schedule Jul 1, 2022
Last updated Python●Matplotlib
Tags tocTable of Contents
expand_more Basic example of plotting scatter plot with categories
To plot a scatter plot with categories or classes in Matplotlib, use the following code:
import matplotlib.pyplot as pltimport pandas as pd
labels = ['A','B','A','C']arr_int_classes = pd.Categorical(labels).codesscatter = plt.scatter([5,2,3,3], [1,2,4,1], c=arr_int_classes)plt.legend(handles=scatter.legend_elements()[0], labels=arr_str_labels)plt.show()
Here, we are first converting our string labels into numerical values using Pandas' Categorical(~)
function:
arr_int_classes = pd.Categorical(labels).codesarr_int_classes
array([0, 1, 0, 2], dtype=int8)
This results in the following plot:

Plotting scatter plot with categories using custom colors
To plot a scatter plot with categories, use ListedColormap
:
import matplotlib.pyplot as pltfrom matplotlib.colors import ListedColormapimport pandas as pd
labels = ['A','B','A','C']arr_int_classes = pd.Categorical(labels).codescolours = ListedColormap(['g','blue','#EA131B'])scatter = plt.scatter([5,2,3,3], [1,2,4,1], c=arr_int_classes, cmap=colours)plt.legend(handles=scatter.legend_elements()[0], labels=arr_str_labels)plt.show()
This produces the following plot:

Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
Ask a question or leave a feedback...
0
0
0
Enjoy our search