【问题标题】:Python visualization - histogramsPython 可视化 - 直方图
【发布时间】:2020-04-14 14:45:19
【问题描述】:

以下两个问题与我正在尝试构建的直方图有关。

1) 我希望垃圾箱如下:
[0-10,10-20,...,580-590, 590-600]。我尝试了以下代码:

 bins_range=[]                                                                                   
 for i in range(0,610,10):
    bins_range.append(i)                                                   
 plt.hist(df['something'], bins=bins_range, rwidth=0.95)

我希望看到上面的 bin 以及每个 bin 对应的样本数量,但我只得到了 10 个 bin(作为默认参数)。

2) 如何更改 y 轴,如下所示:假设我的最大 bin 包含 40 个样本,因此我希望 y 轴上的 40 个不是 40,而是 100%,其他相应。即,30 为 75%,20 为 50%,依此类推。

【问题讨论】:

    标签: python-3.x histogram data-visualization


    【解决方案1】:

    您的代码似乎工作正常。您甚至可以将range 命令直接传递给hist 的bins 参数。

    要获得 y 轴的百分比,我认为您需要通过两次:首先计算 bin 以了解最高 bin 包含多少。然后,使用1/highest 作为权重进行绘图。有一个 numpy np.hist 无需绘图即可完成所有计算。

    使用PercentFormatter() 以百分比显示轴。它得到一个参数来告诉 100% 代表多少。使用PercentFormatter(max(hist)) 将最大值设为 100%。如果只希望总数为 100%,只需传递PercentFormatter(len(x)),无需计算两次直方图。由于内部 y 轴仍在值中,因此刻度不会显示在所需位置。您可以使用plt.yticks(np.linspace(0, max(hist), 11)) 来获得每 10% 的刻度。

    要在条之间获得更好的分隔,您可以设置明确的边缘颜色。最好没有rwidth=0.95

    示例代码:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.ticker import PercentFormatter
    
    x = np.random.rayleigh(200, 50000)
    hist, bins = np.histogram(x, bins=range(0, 610, 10))
    plt.hist(x, bins=bins, ec='white', fc='darkorange')
    plt.gca().yaxis.set_major_formatter(PercentFormatter(max(hist)))
    plt.yticks(np.linspace(0, max(hist), 11))
    
    plt.show()
    

    PS:要使用 matplotlib 的标准 yticks,并且 y 轴也在内部以百分比表示,您可以使用 hist 的 weights 参数。当您想要以交互方式调整大小或缩放绘图,或者需要特定百分比的水平线时,这会很方便。

    plt.hist(x, bins=bins, ec='white', fc='dodgerblue', weights=np.ones_like(x)/max(hist))
    plt.gca().yaxis.set_major_formatter(PercentFormatter(1))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-10
      • 1970-01-01
      • 2017-01-01
      • 2014-07-08
      • 1970-01-01
      • 2013-01-25
      • 1970-01-01
      相关资源
      最近更新 更多