python - 堆叠直方图不会堆叠

标签 python graph matplotlib plot scikit-learn

我正在尝试运行以下代码:

variable_values = #numpy vector, one dimension, 5053 values between 1 and 0.
label_values = #numpy vector, one dimension, 5053 values, discrete value of either 1 OR 0.
x = variable_values[variable_values != '?'].astype(float)
y = label_values[variable_values != '?'].astype(float)

print np.max(x) #prints 0.90101
print np.max(y) #prints 1.0


N = 5053
ind = np.arange(N)    # the x locations for the groups
width = 0.45       # the width of the bars: can also be len(x) sequence
n, bins, patches = plt.hist(x, 5, stacked=True, normed = True)

#Stack the data
plt.figure()
plt.hist(x, bins, stacked=True, normed = True)
plt.hist(y, bins, stacked=True, normed = True)
plt.show()

我想要实现的是下图:

enter image description here

根据 label 的值是 1 还是 0,每个条上的颜色分开。

不幸的是,我目前的输出是:

Output

这有两点不正确 - 首先它没有正确堆叠。其次,Y 轴上的值上升到 1.6,但我相信 Y 轴应该包含属于每个子组的数据 block 的数量(因此,如果所有数据 block 的值都为 0-0.25,则唯一显示数据的栏将是第一个)。

最佳答案

variable_values = #numpy vector, one dimension, 5053 values between 1 and 0.

label_values = #numpy vector, one dimension, 5053 values, discrete value of either 1 OR 0.

您正在尝试对 x 和 y 使用相同的 bin。 x 可能从 0-1 不包括边缘。所以 y 不在您正在绘制的箱子范围内。

它是 1.6,因为您选择了标准化绘图。将该参数设置为 false 以获取实际计数。

这应该可以解决大部分问题:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.random(5053)
y = np.random.random_integers(0,1, 5053)

# x = variable_values[variable_values != '?'].astype(float)
# y = label_values[variable_values != '?'].astype(float)

print np.max(x) #prints 0.90101
print np.max(y) #prints 1.0


N = 5053
ind = np.arange(N)    # the x locations for the groups
width = 0.45       # the width of the bars: can also be len(x) sequence
n, bins, patches = plt.hist(x, 5, stacked=True, normed = True)

bins[0] = 0
bins[-1] = 1

#Stack the data
plt.figure()
plt.hist(y, bins, stacked=True, normed = False)
plt.hist(x, bins, stacked=True, normed = False)
plt.show()

关于python - 堆叠直方图不会堆叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21765357/

相关文章:

python - 参数化 pandas 数据框名称

python - 迁移 admin.0001_initial 在其对数据库 'default' 的依赖 app.0001_initial 之前应用

python - 并行迭代文档行

c++ - 使用图表的机场旅行

python - 动画图到动画 Gif (Python)

python - 在 matplotlib 3d 散点图中更改数据点的颜色并通过按键将其删除

python - 检查 Jinja2 模板中的 Python 字典中是否存在 key

algorithm - 具有加权顶点的树中最小权重的顶点覆盖

graph - 收紧点图使其更对称

python - 使用顶点数组 Python (Matplotlib) 绘制 3D 多边形