如何在python中规范化2d直方图?



我正在尝试绘制二维直方图。直方图基本上是一个星系,我有每个发光点的点。我已经绘制了直方图,但它没有正确地规范化,因为颜色栏的值应该从0到1。我该如何解决这个问题?

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import kde
fig, axes = plt.subplots(ncols=2, nrows=1, figsize=(20, 8))
data1 = pd.read_csv('mydata.txt', sep='s+', header=None)
az1 = data1[0]
el1 = data1[1]
nbins = 250
hist1 = axes[0].hist2d(az1, el1, bins=nbins, cmap='magma', density=True)

fig.colorbar(hist1[3], ax = axes)

我尝试了函数hist2D,但我没有找到一种方法来标准化的结果。所以我建议使用numpy模块的图表:np.nistogram2d,在那里你可以提取结果,然后在显示它之前将输出归一化。下面是一个带有随机数的示例:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import kde
fig, axes = plt.subplots(ncols=2, nrows=1, figsize=(20, 8))
# data1 = pd.read_csv('mydata.txt', sep='s+', header=None)
N=10000
az1 = np.random.random(N)
el1 = np.random.random(N)
nbins = 250
hist1 = axes[0].hist2d(az1, el1, bins=nbins, cmap='magma', density=True)
fig.colorbar(hist1[3], ax = axes)

H, xedges, yedges = np.histogram2d(el1, az1, bins=(nbins, nbins),density=True )
# H_normalized = H/float(az1.shape[0]) # the integral over the histogrm is 1
H_normalized = H/H.max((0,1)) # the max value of the histogrm is 1
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
im = axes[1].imshow(H_normalized, extent=extent, cmap='magma', interpolation='none',origin ='lower')
fig.colorbar(im, ax=axes[1])
plt.show()

最新更新