How to display the sum of three 2D histograms with imshow()?

Viewed 108

I am trying to produce a plot using imshow. The desired behavior is that each gaussian would be centered around the coordinates given, for example, the first peak would be (53,74) with a standard deviation in the x and y directions of 3.14. Instead, the actual behavior is that imshow stacks all three peaks on top of one another at (50,50). I would appreciate any help. I have tried looking this up and looking through each of the parameters at https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html.

import matplotlib.pyplot as plt
import numpy as np

num = 100000
xs1 = np.random.normal(loc=53, scale=3.14, size=num)
ys1 = np.random.normal(loc=74, scale=3.14, size=num)
xs2 = np.random.normal(loc=62, scale=4, size=num)
ys2 = np.random.normal(loc=31, scale=4, size=num)
xs3 = np.random.normal(loc=39, scale=4.5, size=num)
ys3 = np.random.normal(loc=45, scale=4.5, size=num)

data1 = np.histogram2d(xs1, ys1, bins=112)
data2 = np.histogram2d(xs2, ys2, bins=112)
data3 = np.histogram2d(xs3, ys3, bins=112)
total = data1[0] + data2[0] + data3[0] + 900
plt.imshow(data1[0] + data2[0] + data3[0], aspect="auto", )
plt.show()
1 Answers

To add up the 3 histograms, they need exactly the same bins. For example calculated using the global minimum and maximum.

Further, the dimensions of the histograms has x first, so the result needs to be transposed.

imshow() is peculiar, and defaults to start rendering at the top. origin='lower' sets it correct here. To show the coordinates, extent= can be used.

import matplotlib.pyplot as plt
import numpy as np

num = 100000 
xs1 = np.random.normal(loc=53, scale=3.14, size=num)
ys1 = np.random.normal(loc=74, scale=3.14, size=num)
xs2 = np.random.normal(loc=62, scale=4, size=num)
ys2 = np.random.normal(loc=31, scale=4, size=num)
xs3 = np.random.normal(loc=39, scale=4.5, size=num)
ys3 = np.random.normal(loc=45, scale=4.5, size=num)

xmin = min(xs1.min(), xs2.min(), xs3.min())
ymin = min(ys1.min(), ys2.min(), ys3.min())
xmax = max(xs1.max(), xs2.max(), xs3.max())
ymax = max(ys1.max(), ys2.max(), ys3.max())
bins = (np.linspace(xmin, xmax, 112), np.linspace(ymin, ymax, 112))

data1 = np.histogram2d(xs1, ys1, bins=bins)
data2 = np.histogram2d(xs2, ys2, bins=bins)
data3 = np.histogram2d(xs3, ys3, bins=bins)
plt.imshow((data1[0] + data2[0] + data3[0]).T, extent=[xmin, xmax, ymin, ymax],
           aspect="auto", origin='lower', cmap='inferno')
plt.show()

imshow of 2d histograms

Related