简体   繁体   English

如何标准化 python 中的二维直方图?

[英]How to normalize a 2d histogram in python?

I'm trying to plot a 2d histogram.我正在尝试 plot 二维直方图。 The histogram is basically a galaxy and I have the points of each luminous point.直方图基本上是一个星系,我有每个发光点的点。 I have plotted the histogram but it's not properly normalized, as the values of the colorbar should go from 0 to 1. How can I fix this?我已经绘制了直方图,但它没有正确标准化,因为颜色条的值应该是 go 从 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)

I tried with the function hist2D but I didn't find a way to normalized the result with it.我尝试使用 function hist2D ,但我没有找到用它标准化结果的方法。 So what I suggest is using the hitrogram from the numpy modul: np.nistogram2d where you can extract the result and then normalized the output before display it.所以我建议使用numpy模块中的直方图: np.nistogram2d ,您可以在其中提取结果,然后在显示之前对 output 进行归一化。 Here an example with random numbers:这里有一个随机数的例子:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM