Home > Backend Development > Python Tutorial > How Can I Color Scatter Markers by Values of a Third Variable in Matplotlib?

How Can I Color Scatter Markers by Values of a Third Variable in Matplotlib?

Patricia Arquette
Release: 2024-11-15 10:54:02
Original
389 people have browsed it

How Can I Color Scatter Markers by Values of a Third Variable in Matplotlib?

Coloring Scatter Markers by Values of a Third Variable

In matplotlib, scatterplots can be used to visualize relationships between data points. To add more depth to these plots, points can be shaded according to a third variable. Below is a straightforward approach for achieving this.

The code snippet below demonstrates how to create a scatterplot where points are shaded according to a third variable:

plt.scatter(w, M, c=p, marker='s')
Copy after login

Here, w and M represent data points, while p signifies the variable used for shading.

To display the plot in grayscale, remove the color specification and utilize a grayscale colormap:

import matplotlib.pyplot as plt

# Generate data...
x = np.random.random(10)
y = np.random.random(10)

# Plot...
plt.scatter(x, y, c=y, s=500)
plt.gray()

plt.show()
Copy after login

This code uses the plt.gray() method to automatically assign grayscale values to the points.

Alternatively, one can specify a specific grayscale colormap through the cmap keyword argument in scatter. The options include 'gray', 'gist_yarg', 'binary', and others. The reversed version of a colormap can be chosen by adding "_r" to its name.

plt.scatter(x, y, c=y, s=500, cmap='gray')
Copy after login

The above is the detailed content of How Can I Color Scatter Markers by Values of a Third Variable in Matplotlib?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template