how to color plt.scatter plot points based on gradient in python

To color the points in a plt.scatter plot based on a gradient, you can specify the c parameter as an array with values ranging from 0 to 1. Then, you can use a colormap to map these values to colors.

Here's an example:

main.py
import matplotlib.pyplot as plt
import numpy as np

# Generate random data
x = np.random.rand(100)
y = np.random.rand(100)
colors = np.random.rand(100)

# Create scatter plot
plt.scatter(x, y, c=colors, cmap='viridis')

# Add colorbar
plt.colorbar()

# Display the plot
plt.show()
281 chars
17 lines

In this example, I used the np.random.rand function to generate random data for the x and y coordinates, as well as the colors. The c parameter of plt.scatter is set to the array of colors. I also specified the cmap parameter as 'viridis' to use the Viridis colormap.

You can choose a different colormap by specifying a different value for cmap. You can explore the available colormaps in the matplotlib.cm module.

Running the code above will produce a scatter plot where the points are color-coded based on the gradient of the colors array.

gistlibby LogSnag