Matplotlib,从三个不等长的数组创建堆叠直方图 [英] Matplotlib, creating stacked histogram from three unequal length arrays

查看:32
本文介绍了Matplotlib,从三个不等长的数组创建堆叠直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个堆叠的直方图.如果我有一个由三个等长数据集组成的二维数组,这很简单.下面的代码和图像:

将 numpy 导入为 np从 matplotlib 导入 pyplot 作为 plt#创建包含1,000个样本的3个数据集亩,西格玛 = 200, 25x = mu + sigma*np.random.randn(1000,3)#堆叠数据plt.figure()n,垃圾箱,补丁= plt.hist(x,30,堆叠=真,密度=真)plt.show()

但是,如果我尝试使用具有不同长度的三个数据集的相似代码,结果将是一个直方图覆盖了另一个.有什么方法可以处理混合长度数据集的堆叠直方图?

  ##接上###现在作为三个独立的数组x1 = mu + sigma*np.random.randn(990,1)x2 = mu + sigma * np.random.randn(980,1)x3 = mu + sigma*np.random.randn(1000,1)#堆叠数据plt.figure()plt.hist(x1,bins,stacked=True,密度=True)plt.hist(x2,bins,stacked=True,密度=True)plt.hist(x3,装箱,堆叠=真,密度=真)plt.show()

解决方案

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

##接上###现在作为三个独立的数组x1 = mu + sigma * np.random.randn(990,1)x2 = mu + sigma * np.random.randn(980,1)x3 = mu + sigma * np.random.randn(1000,1)#堆叠数据plt.figure()plt.hist([x1,x2,x3], bins,stacked=True, density=True)plt.show()

I'd like to create a stacked histogram. If I have a single 2-D array, made of three equal length data sets, this is simple. Code and image below:

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, density = True)
plt.show()

However, if I try similar code with three data sets of a different length the results are that one histogram covers up another. Is there any way I can do the stacked histogram with mixed length data sets?

##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, density = True)
plt.hist(x2, bins, stacked=True, density = True)
plt.hist(x3, bins, stacked=True, density = True)
plt.show()

解决方案

Well, this is simple. I just need to put the three arrays in a list.

##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, density=True)
plt.show()

这篇关于Matplotlib,从三个不等长的数组创建堆叠直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆