1

我需要使用 Matplotlib 绘制一个 loglog 直方图(bot x 和 y 以 log10 比例),但以下代码没有显示我想要的输出:

import matplotlib.pyplot as plt
import numpy as np
fig, ax1 = plt.subplots()
# suppose to have an array x
ax1.hist(x, ec='white', color="red")
plt.xscale("log")
plt.yscale("log")
plt.show()

我想要的输出是一个直方图,其中 x=np.log10(x) 和等效 y=np.log10(y),其中 y 中的每个元素是每个 bin 的高度。我什至尝试使用条形图,但我无法解决重叠箱的问题: 在此处输入图像描述

   import matplotlib.pyplot as plt
    import numpy as np
    frequency_dict = Counter(x)
    new_x = list(frequency_dict.keys())
    y = list(frequency_dict.values())
    ax1.bar(np.log10(new_x), np.log10(y), ec='white', color="red")
    plt.show()
4

2 回答 2

1

您可以创建在日志空间中均匀分布的 bin。这些 bin 边界可以用 来计算np.logspace(min, max, num_bins)

from matplotlib import pyplot as plt
import numpy as np

x = np.abs(np.random.normal(500, 200, 1000))
assert x.min() > 0, "all values need to be positive for log scale"

plt.hist(x, bins=np.logspace(np.log10(x.min()), np.log10(x.max()), 15), ec='white', color="red")
plt.loglog()

plt.show()

左侧是线性轴的直方图,右侧是对数轴的直方图。两个直方图都使用对数样式的 bin。

演示图

于 2020-04-28T21:07:47.760 回答
0

您可以在 hist 函数中使用“log = True”来设置对数刻度的 y 轴。您可以在创建直方图之前手动记录 x 数据。所以这是一个展示如何做到这一点的例子。我希望这就是你要找的。

import matplotlib.pyplot as plt
import numpy as np

# Simulate a normally distributed dataset
x = np.random.normal(loc = 500, scale = 200, size = 100)

fig, ax = plt.subplots(ncols = 2, figsize=(12,3))
ax[0].hist(x, ec='white', color="red", log = False)
ax[0].set_xlabel('x')
ax[0].set_ylabel('Freq counts')

ax[1].hist(np.log10(x), ec='white', color="red", log = True)
ax[1].set_xlabel('log10(x)')
ax[1].set_ylabel('Freq counts in log scale')

plt.show()

这导致

在此处输入图像描述

于 2020-04-28T19:34:16.687 回答