Home > Backend Development > Python Tutorial > How to Create a Custom Discrete Colorbar for a Matplotlib Scatterplot?

How to Create a Custom Discrete Colorbar for a Matplotlib Scatterplot?

DDD
Release: 2024-10-24 18:36:29
Original
1184 people have browsed it

How to Create a Custom Discrete Colorbar for a Matplotlib Scatterplot?

Custom Discrete Colorbar for Matplotlib Scatterplot

In Matplotlib, creating a discrete colorbar for a scatterplot allows you to represent data points with unique colors based on their integer tag values. To achieve this, a custom discrete colormap and a BoundaryNorm can be employed.

Let's construct a scatterplot with random x and y data, and assign integer tags ranging from 0 to 20:

<code class="python">import matplotlib.pyplot as plt
import numpy as np

x = np.random.rand(20)
y = np.random.rand(20)
tag = np.random.randint(0, 20, 20)</code>
Copy after login

Initially, using the default settings, the colorbar displays a continuous range of colors:

<code class="python">plt.scatter(x, y, c=tag)
plt.colorbar()</code>
Copy after login

To create a discrete colorbar, we'll use a BoundaryNorm to define the bounds of the colormap. We also want to ensure that the tag value of 0 is represented by a gray color:

<code class="python">bounds = np.linspace(0, 20, 21)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

cmaplist = [cmap(i) for i in range(cmap.N)]
cmaplist[0] = (.5, .5, .5, 1.0)

cmap = mpl.colors.LinearSegmentedColormap.from_list(
    'Custom cmap', cmaplist, cmap.N)</code>
Copy after login

The updated scatterplot with the discrete colorbar looks like this:

<code class="python">scat = ax.scatter(x, y, c=tag, s=np.random.randint(100, 500, 20),
                  cmap=cmap, norm=norm)

# Add the discrete colorbar
ax2 = fig.add_axes([0.95, 0.1, 0.03, 0.8])
cb = plt.colorbar.ColorbarBase(ax2, cmap=cmap, norm=norm,
    spacing='proportional', ticks=bounds, boundaries=bounds, format='%1i')</code>
Copy after login

This approach provides a well-defined discrete colorbar for your scatterplot, where each tag value is represented by a unique color, including a gray color for tag value 0.

The above is the detailed content of How to Create a Custom Discrete Colorbar for a Matplotlib Scatterplot?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template