在 matplotlib 中绘制时,正态分布显得过于密集

2024-03-04

我正在尝试估计数据的概率密度函数。就我而言,数据是形状为 8200 x 8100 的卫星图像。 下面,我向您展示 PDF 的代码(函数“is_outlier”是由在此发布此代码的人借用的)。正如我们所看到的,图 1 中的 PDF 过于密集。我想,这是由于卫星图像由数千个像素组成。这是非常丑陋的。

我的问题是,如何绘制不太密集的 PDF?例如,如图 2 所示。

lst = 'satellite_img.tif' #import the image
lst_flat = lst.flatten() #create 1D array

#the function below removes the outliers
def is_outlier(points, thres=3.5):

    if len(points.shape) == 1:
        points = points[:,None]
    median = np.median(points, axis=0)
    diff = np.sum((points - median)**2, axis=-1)
    diff = np.sqrt(diff)
    med_abs_deviation = np.median(diff)

    modified_z_score = 0.6745 * diff / med_abs_deviation

    return modified_z_score > thres


lst_flat = np.r_[lst_flat]
lst_flat_filtered = lst_flat[~is_outlier(lst_flat)]
fit = stats.norm.pdf(lst_flat_filtered, np.mean(lst_flat_filtered), np.std(lst_flat_filtered))

plt.plot(lst_flat_filtered, fit)
plt.hist(lst_flat_filtered, bins=30, normed=True)
plt.show()

figure 1

enter image description here figure 2


问题在于 PDF 图中的 x 值未排序,因此绘制的线在随机点之间来回移动,从而造成您看到的混乱。

两种选择:

  1. 不要绘制线,只绘制点(如果你有很多点,那就不太好,但会确认我上面所说的是否正确):

    plt.plot(lst_flat_filtered, fit, 'bo')
    
  2. 排序lst_flat_filtered计算 PDF 并绘制它之前的数组:

    lst_flat = np.r_[lst_flat]
    lst_flat_filtered = np.sort(lst_flat[~is_outlier(lst_flat)])  # Changed this line
    fit = stats.norm.pdf(lst_flat_filtered, np.mean(lst_flat_filtered), np.std(lst_flat_filtered))
    
    plt.plot(lst_flat_filtered, fit)
    

以下是一些显示这些行为的最小示例:

重现您的问题:

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

lst_flat_filtered = np.random.normal(7, 5, 1000)

fit = stats.norm.pdf(lst_flat_filtered, np.mean(lst_flat_filtered), np.std(lst_flat_filtered))

plt.hist(lst_flat_filtered, bins=30, normed=True)

plt.plot(lst_flat_filtered, fit)

plt.show()

标绘点

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

lst_flat_filtered = np.random.normal(7, 5, 1000)

fit = stats.norm.pdf(lst_flat_filtered, np.mean(lst_flat_filtered), np.std(lst_flat_filtered))

plt.hist(lst_flat_filtered, bins=30, normed=True)

plt.plot(lst_flat_filtered, fit, 'bo')

plt.show()

对数据进行排序

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

lst_flat_filtered = np.sort(np.random.normal(7, 5, 1000))

fit = stats.norm.pdf(lst_flat_filtered, np.mean(lst_flat_filtered), np.std(lst_flat_filtered))

plt.hist(lst_flat_filtered, bins=30, normed=True)

plt.plot(lst_flat_filtered, fit)

plt.show()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 matplotlib 中绘制时,正态分布显得过于密集 的相关文章

随机推荐