【问题标题】:Python - Averaging out histogramsPython - 平均直方图
【发布时间】:2018-05-13 20:17:26
【问题描述】:

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

【问题讨论】:

  • 是的。它们是 NumPy 数组吗?列表?你试过什么,有代码吗?
  • 请添加您的代码和数据。有可能是的
  • 好吧,现在我想创建第五个直方图,它是其他 4 个直方图的平均值。
  • 添加完整代码.. Planet_Elevations1 是什么??
  • 那应该只是 Elevations1,for 循环循环遍历 numpy 数组的每个位置并给它一个随机数。

标签: python matplotlib histogram


【解决方案1】:

您需要获取组合直方图的频率,然后将它们归一化 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()

【讨论】:

  • 这很好,但这会增加每个直方图的频率。我想平均每个直方图中每个 bin 的频率。
  • 哦。好吧,现在我明白了。我会在几分钟内更新我的答案
  • 可以,确实看起来好多了。谢谢
  • 开头的random.seed(0)是做什么的?我也收到一个值错误“权重应该与 x 具有相同的形状”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-25
  • 2013-04-17
  • 2016-12-21
  • 1970-01-01
  • 2021-05-07
相关资源
最近更新 更多