Use, customize and create categoric palettes in Matplotlib

logo of a chart:Colours

This post explains how to use matplotlib categorical palettes, how to use them in practice and how to create your own.

Matplotlib has built-in tools that make it easy to use categoric palettes by having a set of predefined palettes and functions to create custom ones.

Palettes

When working with colors, it's important to understand the difference between

  • sequential palettes, which are used for ordered/numerical data that progresses from low to high
  • diverging palettes, which are used for ordered/numerical data that has a critical midpoint, such as zero
  • qualitative palettes, which are used for unordered/categorical data

In this post, we'll focus on qualitative palettes. These palettes are used to represent unordered/categorical data, such as different species of animals or different types of fruits.

Available palettes by default

Here are the available default qualitative palettes in matplotlib:

categorical palettes

How to use a qualitative palette

Now let's see how to use them in practice. We start by looking at how they look and then choose the one that fits our taste the best.

import matplotlib.pyplot as plt
plt.get_cmap('Pastel1')
plt.get_cmap('tab20')
plt.get_cmap('Accent')

Let's say you like the Accent palette and want to use to color the points in a scatter plot in matplotlib. Here's how you can do it:

  • Load the necessary libraries
# Load libraries
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import random

# Fix random seed for reproducibility
np.random.seed(1)
  • Create some data
# Create some data
size = 30
data = pd.DataFrame({
   'x': np.random.randn(size),
   'y': np.random.randn(size),
   'cat': random.choices(['A', 'B', 'C'], k=size)
})
data.head()
x y cat
0 1.624345 -0.691661 A
1 -0.611756 -0.396754 B
2 -0.528172 -0.687173 B
3 -1.072969 -0.845206 C
4 0.865408 -0.671246 B
  • Create a scatter plot with the Accent palette
# Iniate a figure for the scatter plot
fig, ax = plt.subplots(dpi=300)

# Define our colormap
cmap = plt.get_cmap('Accent')

# Create a scatter plot with Accent colormap
for i, (cat, df) in enumerate(data.groupby('cat')):
   ax.scatter(df['x'], df['y'], label=cat, color=cmap(i), s=100)

# Add a legend
ax.legend()

# Display the plot
plt.show()

Going further

Palette finder

Browse the color palette finder to find your dream palette!

Related

Animation with python

Animation

Contact & Edit


👋 This document is a work by Yan Holtz. You can contribute on github, send me a feedback on twitter or subscribe to the newsletter to know when new examples are published! 🔥

This page is just a jupyter notebook, you can edit it here. Please help me making this website better 🙏!