user554481
user554481

Reputation: 2109

Specify range of colors for density plot in Matplotlib

The following code:

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde

# Generate fake data
x = np.random.normal(size=1000)
y = x * 3 + np.random.normal(size=1000)

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

# Sort the points by density, so that the densest points are plotted last
idx = z.argsort()
x, y, z = x[idx], y[idx], z[idx]

fig, ax = plt.subplots()
ax.scatter(x, y, c=z, s=50, edgecolor='')
plt.show()

produces a graph like this:

enter image description here

How can I change the theme from red to, say, blue? Something like this:

import seaborn as sns
sns.palplot(sns.color_palette("Blues"))

enter image description here

Upvotes: 0

Views: 2378

Answers (1)

Sheldore
Sheldore

Reputation: 39052

You can assign any color map to scatter plot as follows. Here you will find all the existing colormaps in matplotlib.

The colormap you want is named Blues. You have to import matplotlib.cm to access the color maps and then pass the required color map as an argument to cmap in your scatter plot. Additionally, you can show the color bar for sake of interpretation of the colors. If you want to reverse a color map, just include _r at the end of that color map. For instance, Blues_r will reverse the map with the scale now going from blue (low) to white (high).

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
import matplotlib.cm as cm

# Generate fake data
x = np.random.normal(size=1000)
y = x * 3 + np.random.normal(size=1000)

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

# Sort the points by density, so that the densest points are plotted last
idx = z.argsort()
x, y, z = x[idx], y[idx], z[idx]

fig, ax = plt.subplots()
ax_ = ax.scatter(x, y, c=z, cmap=cm.Blues, s=50, edgecolor='')
plt.colorbar(ax_)

enter image description here

Upvotes: 4

Related Questions