Python平均直方图

2024-07-02 12:07:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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)

Tags: importasnpzerospltrandomhist平均值
1条回答
网友
1楼 · 发布于 2024-07-02 12:07:36

你需要得到组合直方图的频率,然后将它们归一化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

相关问题 更多 >