Python - 平均直方图

时间:2018-05-13 20:17:26

标签: python matplotlib histogram

我在Python中有4个直方图,但是我想创建第5个直方图,它是前四个直方图的平均值(每个bin的频率总和除以4)。有没有办法做到这一点?

import numpy as np
import random
import matplotlib.pyplot as plt

Elevations1 = np.zeros(100)
Elevations2 = np.zeros(100)
Elevations3 = np.zeros(100)
Elevations4 = np.zeros(100)

for a in np.arange(len(Elevations1)):

    Elevations1[a] = random.randrange(-10000, 10000)
    Elevations2[a] = random.randrange(-10000, 10000)
    Elevations3[a] = random.randrange(-10000, 10000)
    Elevations4[a] = random.randrange(-10000, 10000)

 plt.figure(1)
 plt.hist(Elevations1)
 plt.figure(2)
 plt.hist(Elevations2)
 plt.figure(3)
 plt.hist(Elevations3)
 plt.figure(4)
 plt.hist(Elevations4)

1 个答案:

答案 0 :(得分:0)

您需要获取组合直方图的频率,然后将它们标准化为4以获得平均值。您可以执行以下操作:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import random

random.seed(0)

Elevations1 = np.zeros(100)
Elevations2 = np.zeros(100)
Elevations3 = np.zeros(100)
Elevations4 = np.zeros(100)

for a in np.arange(len(Elevations1)):

    Elevations1[a] = random.randrange(-10000, 10000)
    Elevations2[a] = random.randrange(-10000, 10000)
    Elevations3[a] = random.randrange(-10000, 10000)
    Elevations4[a] = random.randrange(-10000, 10000)

df1 = pd.DataFrame(Elevations1)
df2 = pd.DataFrame(Elevations2)
df3 = pd.DataFrame(Elevations3)
df4 = pd.DataFrame(Elevations4)

df_merged = pd.concat([df1, df2, df3, df4], ignore_index=True)

# Get the frequencies of the combined histogram
hist, bins = np.histogram(df_merged)
# Normalize by 4
hist_norm = hist / 4.0


width = 0.9 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2

# plot the Un-normalited frequencies
plt.bar(center, hist, align='center', width=width)
plt.title('Non- Normalized Histogram')
plt.show()

# plot the normalized frequencies
plt.bar(center, hist_norm, align='center', width=width)
plt.title('Normalized Histogram')
plt.show()

1

enter image description here