Python 使用Matplotlib以对数比例绘制直方图
我有一个pandas数据框,它在一系列中具有以下值Python 使用Matplotlib以对数比例绘制直方图,python,pandas,numpy,matplotlib,statistics,Python,Pandas,Numpy,Matplotlib,Statistics,我有一个pandas数据框,它在一系列中具有以下值 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] 我被指示用Python 3.6在Jupyter笔记本中绘制两个直方图。不用担心,对吧 x.plot.hist(bins=8) plt.show() 我选择了8个垃圾箱,因为这对我来说是
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]
我被指示用Python 3.6在Jupyter笔记本中绘制两个直方图。不用担心,对吧
x.plot.hist(bins=8)
plt.show()
我选择了8个垃圾箱,因为这对我来说是最好的。
我还被指示用x的对数绘制另一个直方图
x.plot.hist(bins=8)
plt.xscale('log')
plt.show()
这个直方图看起来很糟糕。我做得不对吗?我试过摆弄这个情节,但我所做的一切似乎都让柱状图看起来更糟。例如:
x.plot(kind='hist', logx=True)
除了将X的对数绘制为直方图外,没有给我任何指示
我真的很感激任何帮助
为了记录在案,我导入了pandas、numpy和matplotlib,并指定绘图应该是内联的
用x的对数绘制另一个直方图
x.plot.hist(bins=8)
plt.xscale('log')
plt.show()
与在对数刻度上绘制x不同。绘制x的对数将是
np.log(x).plot.hist(bins=8)
plt.show()
不同的是x本身的值被转换了:我们看到的是它们的对数
这与在对数比例上绘图不同,在对数比例下,我们保持x不变,但改变水平轴的标记方式(将条向右挤压,将条向左拉伸).在
hist
调用中指定bin=8
,意味着最小值和最大值之间的范围被平均划分为8个bin。在线性尺度上相等的东西在对数尺度上是扭曲的
你能做的就是指定柱状图的箱子,使它们在宽度上不相等,使它们在对数尺度上看起来相等
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()
这里还有一个解决方案,它不需要使用子图或在同一个图像中绘制两个东西
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)
直方图的“糟糕”之处是什么?最好的方法/解决方法就是
plt.hist(np.log(x))
。我会使用logbins=np.geomspace(x.min(),x.max(),8)
来保存键入的所有日志(而bin[0],bin[-1]无论如何都只是min和max)。发布之前应该测试代码-它无法编译,因为没有“:”函数声明之后。而且,在添加它之后,代码仍然不起作用-它只会崩溃。感谢您指出。修正了打字错误。在Python3.5和Python3.8上,代码对我来说都很好。谢谢你的贡献