【问题标题】:Plotting stacked histograms in python using matplotlib使用matplotlib在python中绘制堆叠直方图
【发布时间】:2014-03-12 20:22:54
【问题描述】:

我正在尝试有效地绘制一些数据,以便将其可视化,但我遇到了一些麻烦。我有两个价值观。一个是离散的(0 或 1),称为label。另一个是介于 0 和 1 之间的连续值。我希望创建一个直方图,在 X 轴上会有许多条形图,例如每 0.25 个数据一个,所以四个条形图,其中第一个具有值0-0.25,第二个 0.25-0.5,第三个 0.5-0.75 和第四个 0.75-1。

y 轴将根据标签是 1 还是 0 进行分割,所以我们最终得到如下图:

如果有任何有效、智能的方法来拆分我的数据(而不仅仅是为这些值硬编码四个条),我也会对此感兴趣,尽管这可能需要另一个问题。当我有这个运行的代码时,我会发布它。

我将两个值都存储在 numpy 数组中,如下所示,但我不确定如何绘制这样的图表:

import numpy as np
import pylab as P

variable_values = trainData.get_vector('variable') #returns one dimensional numpy array of vals
label_values = trainData.get_vector('label')
x = alchemy_category_score_values[alchemy_category_score_values != '?'].astype(float) #removing void vals
y = label_values[alchemy_category_score_values != '?'].astype(float)

fig = plt.figure()

plt.title("Feature breakdown histogram")
plt.xlabel("Variable")
plt.xlim(0, 1)
plt.ylabel("Label")
plt.ylim(0, 1)
xvals = np.linspace(0,1,.02)

plt.show()

matplotlib 教程显示了以下代码,大致实现了我想要的,但我无法真正理解它是如何工作的(LINK):

P.figure()

n, bins, patches = P.hist(x, 10, normed=1, histtype='bar', stacked=True)

P.show()

非常感谢任何帮助。谢谢。

编辑:

我现在收到错误:

AssertionError: incompatible sizes: argument 'height' must be length 5 or scalar

我打印了两个 numpy 数组,它们的长度相等,一个是离散的,另一个是连续的。这是我正在运行的代码:

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

print x #printing numpy arrays of equal size, x is continuous, y is discrete. Both of type float now.
print y

N = 5
ind = np.arange(N)    # the x locations for the groups
width = 0.45       # the width of the bars: can also be len(x) sequence

p1 = plt.bar(ind, y,   width, color='r') #error occurs here
p2 = plt.bar(ind, x, width, color='y',
             bottom=x)

plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind+width/2., ('G1', 'G2', 'G3', 'G4', 'G5') )
plt.yticks(np.arange(0,81,10))
plt.legend( (p1[0], p2[0]), ('Men', 'Women') )

plt.show()

【问题讨论】:

  • 您的 x 值必须是二维数组。您是否注意到您提供的链接中的命令x = mu + sigma*P.randn(1000,3)?这用于制作三个堆叠的条形图。
  • 错误来自N变量,即直方图中的柱数。要么写一个 4,要么使用len(x)

标签: python numpy graph matplotlib plot


【解决方案1】:

我认为来自同一个 Matplotlib 库的 this other tutorial 对你来说会更有启发性......

注意第二组数据在调用中多了一个参数:bottom

p1 = plt.bar(ind, menMeans,   width, color='r', yerr=womenStd)
p2 = plt.bar(ind, womenMeans, width, color='y',
             bottom=menMeans, yerr=menStd)

只需将menMeans 替换为x 并将womenMeans 替换为y

【讨论】:

  • 感谢您的回复。在这种情况下我会为 yerr 做什么,我不太明白它是如何工作的 :)
  • yerr 可以省略。它允许您在每个直方图条的顶部放置一个错误范围。它是可选的。
  • 非常感谢您的帮助。我已经更新了我上面的问题。我想我现在很接近但无法弄清楚这个错误消息,你能看到我在这里做错了什么吗?
  • 查看我对这个问题的评论:修复N的值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-25
  • 1970-01-01
  • 2016-06-09
  • 2015-10-25
相关资源
最近更新 更多