【发布时间】: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