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')
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()
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')
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!