Create a complex two-dimensional histogram using different weights

Let's say I want to create a histogram of these particles that is smoothed over a certain range of bin, nbin. Now I have 5 data sets with particles of different masses (each set of x, y has a different mass). Usually a particle position histogram is a simple case (using numpy):

heatmap, xedges, yedges = np.histogram2d(x, y, bins=nbin) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] heatmap = np.flipud(np.rot90(heatmap)) ax.imshow(heatmap, extent=extent) 

However, if I want to add the next batch of particles, they have different masses, and the density will be different. Is there a way to weigh the histogram with some constant, so the constructed floating chart will be a true representation of the density, and not just binings of the total number of particles?

I know that "scales" is a feature, but is this the case of just setting weights = m_i, where m_i is the particle mass for each data set 1-5?

+4
source share
1 answer

The weights parameter expects an array with the same length as x and y . np.histogram2d . It will not translate a constant value, so even though the mass is the same for every np.histogram2d call, you should still use something like

 weights=np.ones_like(x)*mass 

Now one problem that you may encounter if you use bin=nbin is that the edges of the buffer, xedges , yedges may vary depending on the x and y values ​​that you pass to np.histogram2d . If you naively add heat maps together, the end result will accumulate particle density in the wrong places.

So, if you want to call np.histogram2d more than once and add partial heat maps together, you must first determine where you want the edges of the hopper.

For instance:

 import numpy as np import itertools as IT import matplotlib.pyplot as plt N = 50 nbin = 10 xs = [np.array([i,i,i+1,i+1]) for i in range(N)] ys = [np.array([i,i+1,i,i+1]) for i in range(N)] masses = np.arange(N) heatmap = 0 xedges = np.linspace(0, N, nbin) yedges = np.linspace(0, N, nbin) for x, y, mass in IT.izip(xs, ys, masses): hist, xedges, yedges = np.histogram2d( x, y, bins=[xedges, yedges], weights=np.ones_like(x)*mass) heatmap += hist extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] heatmap = np.flipud(np.rot90(heatmap)) fig, ax = plt.subplots() ax.imshow(heatmap, extent=extent, interpolation='nearest') plt.show() 

gives

enter image description here

+4
source

Source: https://habr.com/ru/post/1487481/


All Articles