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

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

DDD
DDDOriginal
2024-10-24 18:36:29968browse

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>

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>

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>

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>

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!

Statement:
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