我试图有效地绘制一些数据,因此我可以将其视觉化,但我遇到了一些麻烦。我有两个值。一个是离散的(0或1),并且被称为label
。另一个值是0到1之间的连续值。我希望创建一个直方图,在X轴上会有很多条,例如每0.25个数据一个,所以有四个条,其中第一个条的值0-0.25,第二个0.25-0.5,第三个0.5-0.75和第四个0.75-1。使用matplotlib在python中绘制堆叠直方图
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教程演示下面的代码大致达到我想要的,但我可以“T真正了解它是如何工作(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值必须是2d数组。你有没有注意到你给的链接中的命令'x = mu + sigma * P.randn(1000,3)'?这是用来制作三个堆叠的酒吧。 –
错误来自'N'变量,它是直方图中的条数。要么写一个4,要么使用'len(x)'。 – logc