how to add a colorbar to a plot

Question:

i have a dataframe with two columns
The one is dif and the other is sza

i have made the following scatter plot

x = df['sza']

y = df['dif']

# Calculate the point density

xy = np.vstack([x,y])

z = gaussian_kde(xy)(xy)

fig, ax = plt.subplots()

ax.scatter(x, y, c=z, s=100)

plt.show()

enter image description here

what i want to do is to add a colorbar that will indicate the point density z that is shown in the plot

how can i do that ?

Asked By: span_path

||

Answers:

To add a colorbar to your plot, you can use the ScalarMappable class from the matplotlib library. Here is an example of how you can modify your code to add a colorbar:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable

x = df['sza']
y = df['dif']

# Calculate the point density
xy = np.vstack([x,y])
z = gaussian_kde(xy)(xy)

fig, ax = plt.subplots()

# Create a scatter plot with a colorbar
sc = ax.scatter(x, y, c=z, s=100)

# Create a ScalarMappable object to represent the colorbar
sm = ScalarMappable(cmap='viridis', norm=plt.Normalize(vmin=z.min(), vmax=z.max()))
sm.set_array([])

# Add the colorbar to the plot
cb = fig.colorbar(sm)
cb.set_label('Point Density')

plt.show()

First, create the scatter plot with the ax.scatter() method as before. Then, we create a ScalarMappable object sm using the viridis colormap and normalized values of z. We also set the array to be empty [] because you do not need it for the plot.

Finally, add the colorbar to the plot with fig.colorbar(sm) and set its label to ‘Point Density’ using cb.set_label().

Answered By: tamarajqawasmeh