【问题标题】:How to scale histogram bar heights in matplotlib / seaborn?如何在 matplotlib / seaborn 中缩放直方图条的高度?
【发布时间】:2021-02-19 06:29:36
【问题描述】:

我的数据集是一个大小为 (m, 1) 的 numpy 数组,我需要 2 个图:a) 标准化的整个数据之一(概率) b) 保持与以前相同的标准化的数据集子集之一。

问题在于,在 b) 情况下,matplotlib 和 seaborn 提供的规范化选项只能“看到”子集,因此它们无法基于整个数据进行规范化。

基本上我想做的是:

bar_height = bar_count / m

样本数据:

array([[-0.00996642],
       [ 0.00407526],
       [ 0.00547561],
       ...,
       [ 0.05205999],
       [ 0.00224144],
       [ 0.01201942]])

【问题讨论】:

  • sns.histplot()有一个参数stat={“count”, “frequency”, “density”, “probability”}
  • 我知道。问题是我需要用 A 的“概率”来绘制 B。B 是 A 的子集
  • 所以我需要手动计算 bins、bar_widths、bar_heights 并将它们绘制在条形图中。我想知道直方图中是否有条形缩放选项。

标签: python numpy matplotlib seaborn histogram


【解决方案1】:

您可以使用np.histogram() 计算直方图,然后使用plt.bar() 绘制条形:

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

sns.set()
m = 200
samples = np.random.rand(1000)
hist_values, bin_edges = np.histogram(samples)
plt.bar(x=bin_edges[:-1], height=hist_values / m, width=np.diff(bin_edges), align='edge')
plt.show()

【讨论】:

    猜你喜欢
    • 2017-02-18
    • 1970-01-01
    • 2010-11-16
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 2015-10-29
    • 2017-12-07
    • 1970-01-01
    相关资源
    最近更新 更多