Home > Article > Backend Development > How to Color Scatter Markers Based on a Third Variable in Matplotlib?
Scatterplots are an effective way to visualize the relationship between two or more variables. When you have a third variable that you want to represent, you can use it to color the markers in your scatterplot. Here's how to achieve grayscale coloring in Matplotlib:
To color your markers in greyscale, you can specify a grayscale colormap to the scatter function. A colormap defines the range of colors that will be used to shade the markers. Here's an example:
import numpy as np import matplotlib.pyplot as plt # Generate sample data w = np.random.rand(10) M = np.random.rand(10) p = np.random.rand(10) plt.scatter(w, M, c=p, s=500, cmap='gray') # s is the marker size plt.show()
In this example:
Alternatively, if you prefer a wider selection of grayscale colormaps, you can specify the cmap parameter directly. There are numerous pre-made grayscale colormaps available, such as gray, gist_yarg, and binary. To use the reversed version of any colormap, append "_r." For instance, gray_r instead of gray. Here's an example using the gray colormap:
plt.scatter(w, M, c=p, s=500, cmap='gray')
The above is the detailed content of How to Color Scatter Markers Based on a Third Variable in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!