2013-08-26 47 views
29

Tôi muốn tạo một biểu đồ xếp chồng lên nhau. Nếu tôi có một mảng 2-D, được tạo thành từ ba tập dữ liệu có chiều dài bằng nhau, điều này rất đơn giản. Mã và hình ảnh dưới đây:Matplotlib, tạo biểu đồ xếp chồng lên nhau từ ba mảng chiều dài không bằng nhau

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

Tuy nhiên, nếu tôi cố gắng mã tương tự với ba bộ dữ liệu của một độ dài khác nhau kết quả là có một biểu đồ bao che nhau. Có cách nào tôi có thể làm biểu đồ xếp chồng lên nhau với các tập dữ liệu độ dài hỗn hợp không?

##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

Trả lời

48

Vâng, đây là đơn giản. Tôi chỉ cần đặt ba mảng trong một danh sách.

##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

Cách tốt nhất để thêm chú thích cho 'x1',' x2' và 'x3' là gì? – Boern

+0

plt.hist ([x1, x2, x3], thùng, xếp chồng lên nhau = True, color = ["red", "blue", "violet"], normed = True); plt.legend ({label1: "red", label2: "blue", label3: "violet"}) –

Các vấn đề liên quan