Eruditio
Eruditio

Reputation: 147

Density by color in scatter plot with histogram axes

I have 2 separate plot features that I want to combine.

The first is adding color based on density. The second is straddling the scatter plot with its respective marginals (I would prefer left and bottom instead of top and right, but I can likely get that myself)

I get errors when trying to add z=c option to the combo-scatter plot.

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

x = np.random.normal(0,1,500).reshape(-1)
y = x + 0.3*np.random.normal(0,1,500).reshape(-1)


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


plt.scatter(x,y,c=z)
plt.show()



scatter_axes = plt.subplot2grid((3, 3), (1, 0), rowspan=2, colspan=2)
x_hist_axes = plt.subplot2grid((3, 3), (0, 0), colspan=2,
                           sharex=scatter_axes)
y_hist_axes = plt.subplot2grid((3, 3), (1, 2), rowspan=2,
                           sharey=scatter_axes)

nbins = 30
scatter_axes.plot(x, y, '.')
x_hist_axes.hist(x, nbins)
y_hist_axes.hist(y,nbins, orientation='horizontal')
plt.show()

How can I get density color in the subplot?

Upvotes: 0

Views: 324

Answers (1)

Jan K
Jan K

Reputation: 4150

You need to use the scatter method rather than the plot method.

scatter_axes.scatter(x, y, c=z)

Upvotes: 1

Related Questions