使用Matplotlib在对数刻度上绘制直方图

Tom*_*mmy 14 python statistics numpy matplotlib pandas

我有一个pandas DataFrame,它在一个系列中具有以下值

x = [2, 1, 76, 140, 286, 267, 60, 271, 5, 13, 9, 76, 77, 6, 2, 27, 22, 1, 12, 7, 19, 81, 11, 173, 13, 7, 16, 19, 23, 197, 167, 1]
Run Code Online (Sandbox Code Playgroud)

我被指示用Python 3.6在Jupyter笔记本中绘制两个直方图.没汗水吧?

x.plot.hist(bins=8)
plt.show()
Run Code Online (Sandbox Code Playgroud)

我选择了8箱,因为这对我来说最好.我还被指示使用x的日志绘制另一个直方图.

x.plot.hist(bins=8)
plt.xscale('log')
plt.show()
Run Code Online (Sandbox Code Playgroud)

这个直方图看起来很可怕.我没有做对吗?我试图摆弄情节,但我尝试的一切似乎都让直方图看起来更糟.例:

x.plot(kind='hist', logx=True)
Run Code Online (Sandbox Code Playgroud)

除了将X的对数绘制为直方图之外,我没有得到任何指示.

我非常感谢任何帮助!

为了记录,我导入了pandas,numpy和matplotlib,并指定绘图应该是内联的.

Imp*_*est 24

bins=8hist通话中指定意味着最小值和最大值之间的范围被平均分成8个区间.在线性标度上相等的是在对数标度上失真.

您可以做的是指定直方图的区间,使得它们的宽度不相等,使得它们在对数刻度上看起来相等.

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

x = [2, 1, 76, 140, 286, 267, 60, 271, 5, 13, 9, 76, 77, 6, 2, 27, 22, 1, 12, 7, 
     19, 81, 11, 173, 13, 7, 16, 19, 23, 197, 167, 1]
x = pd.Series(x)

# histogram on linear scale
plt.subplot(211)
hist, bins, _ = plt.hist(x, bins=8)

# histogram on log scale. 
# Use non-equal bin sizes, such that they look equal on log scale.
logbins = np.logspace(np.log10(bins[0]),np.log10(bins[-1]),len(bins))
plt.subplot(212)
plt.hist(x, bins=logbins)
plt.xscale('log')
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 我会使用 `logbins = np.geomspace(x.min(), x.max(), 8)` 来保存输入所有这些日志(并且 bins[0], bins[-1] 只是 min 和 max 反正)。 (10认同)

小智 7

用x的对数绘制另一个直方图。

与在对数标度上绘制x不同。绘制x的对数将是

np.log(x).plot.hist(bins=8)
plt.show()
Run Code Online (Sandbox Code Playgroud)

历史

区别在于x本身的值已转换:我们正在查看它们的对数。

这是绘制对数刻度,我们保持X相同,但改变横轴被标记的方式不同(其挤压酒吧的权利,那些延伸到左)。


Rah*_*haw 5

这是又一个解决方案,无需使用子图或在同一图像中绘制两件事。

import numpy as np
import matplotlib.pyplot as plt

def plot_loghist(x, bins):
  hist, bins = np.histogram(x, bins=bins)
  logbins = np.logspace(np.log10(bins[0]),np.log10(bins[-1]),len(bins))
  plt.hist(x, bins=logbins)
  plt.xscale('log')

plot_loghist(np.random.rand(200), 10)
Run Code Online (Sandbox Code Playgroud)

历史图示例

  • python 3.8 也适合我。感谢您的有用贡献 (3认同)
  • 您应该在发布代码之前对其进行测试 - 它无法编译,因为函数声明后没有“:”。而且,添加后,代码仍然无法工作 - 它只会崩溃。 (2认同)
  • 感谢您的指出。修正了拼写错误。该代码在 python 3.5 上对我来说工作得很好 (2认同)