Python Matplotlib,从三个不等长数组创建堆叠直方图

Python Matplotlib,从三个不等长数组创建堆叠直方图,python,matplotlib,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, patch

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

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()

然而,如果我用三个不同长度的数据集尝试类似的代码,结果是一个直方图掩盖了另一个直方图。是否有任何方法可以使用混合长度数据集进行叠加直方图

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

这很简单。我只需要把这三个数组放到一个列表中

##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()
  • 如果是选项,则可以将阵列加载到数据框中并打印
  • 使用熊猫的好处是,数据现在以一种有用的格式用于附加分析和其他绘图
  • 下面的代码将为每个数组创建一个
    数据帧的
    列表
    ,然后将这些数组合并到一个列表中。
    • 这是创建长度不等的数组的数据帧的正确方法。
      • 有更多的方法从长度不等的数组创建数据帧
    • 对于等长数组,使用df=pd.DataFrame({'x1':x1,'x2':x2,'x3':x3})
  • 使用,它使用
    matplotlib
    作为默认打印引擎。
    • matplotlib中的
      normed
      已替换为
      density
  • 将熊猫作为pd导入
    将numpy作为np导入
    #创建不均匀阵列
    μ,σ=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)
    #创建数据帧;枚举用于生成列名
    df=pd.concat([pd.DataFrame(a,columns=[f'x{i}']),用于枚举([x1,x2,x3],1)],轴=1)
    #绘制数据
    df.plot.hist(堆叠=真,箱子=30,密度=真,figsize=(10,6),网格=真)
    

    分别为
    x1
    x2
    x3
    添加图例的最佳方法是什么?plt.hist([x1,x2,x3],bin,stacked=True,color=[“红色”,“蓝色”,“紫色”,normed=True);plt.图例({label1:“红色”,label2:“蓝色”,label3:“紫色”})