2013-08-26 43 views
29

我想创建堆叠直方图。如果我有一个由三个等长数据集组成的单个二维数组,这很简单。代码和图片如下:Matplotlib,从三个不等长阵列创建堆叠直方图

import numpy as np 
from matplotlib import pyplot as plt 

# create 3 data sets with 1,000 samples 
mu, sigma = 200, 25 
x = mu + sigma*np.random.randn(1000,3) 

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

enter image description here

但是,如果我尝试类似的代码,用三组数据不同长度的结果是一个直方图涵盖了另一个。有什么办法可以用混合长度的数据集进行叠加直方图吗?

##Continued from above 
###Now as three separate arrays 
x1 = mu + sigma*np.random.randn(990,1) 
x2 = mu + sigma*np.random.randn(980,1) 
x3 = mu + sigma*np.random.randn(1000,1) 

#Stack the data 
plt.figure() 
plt.hist(x1, bins, stacked=True, normed = True) 
plt.hist(x2, bins, stacked=True, normed = True) 
plt.hist(x3, bins, stacked=True, normed = True) 
plt.show() 

enter image description here

回答

48

嗯,这很简单。我只需要将这三个数组放在一个列表中。

##Continued from above 
###Now as three separate arrays 
x1 = mu + sigma*np.random.randn(990,1) 
x2 = mu + sigma*np.random.randn(980,1) 
x3 = mu + sigma*np.random.randn(1000,1) 

#Stack the data 
plt.figure() 
plt.hist([x1,x2,x3], bins, stacked=True, normed = True) 
plt.show() 
+2

分别为'x1','x2'和'x3'添加图例的最佳方法是什么? – Boern

+0

plt.hist([x1,x2,x3],bins,stacked = True,color = [“red”,“blue”,“violet”],normed = True); plt.legend({label1:“red”,label2:“blue”,label3:“violet”}) –