Matplotlib,从三个不等长度的数组创建堆积直方图

ncR*_*ert 47 python 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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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

##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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

ncR*_*ert 75

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

##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()
Run Code Online (Sandbox Code Playgroud)

  • plt.hist([x1,x2,x3],垃圾箱,堆叠=真,颜色= [“红色”,“蓝色”,“紫”],标准= True);plt.legend({label1:“ red”,label2:“ blue”,label3:“ violet”}) (5认同)
  • 分别为"x1","x2"和"x3"添加图例的最佳方法是什么? (4认同)

Tre*_*ney 8

import pandas as pd
import numpy as np

# create the uneven arrays
mu, sigma = 200, 25
np.random.seed(365)
x1 = mu + sigma*np.random.randn(990, 1)
x2 = mu + sigma*np.random.randn(980, 1)
x3 = mu + sigma*np.random.randn(1000, 1)

# create the dataframe; enumerate is used to make column names
df = pd.concat([pd.DataFrame(a, columns=[f'x{i}']) for i, a in enumerate([x1, x2, x3], 1)], axis=1)

# plot the data
df.plot.hist(stacked=True, bins=30, density=True, figsize=(10, 6), grid=True)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述