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)
pandas
是一个选项,则可以将数组加载到数据框中并进行绘制。list
of DataFrames
with pandas.DataFrame
, ,然后将concat
数组组合在一起形成列表理解。
df = pd.DataFrame({'x1': x1, 'x2': x2, 'x3': x3})
pandas.DataFrame.plot
,它用作matplotlib
默认绘图引擎。
normed
已被替换density
为matplotlib
density
中的参数。matplotlib.pyplot.hist
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)