如何在Python中制作对数-对数直方图
给定一组数值,我想根据这些数值的出现次数画一个对数-对数的直方图。我只知道怎么对x轴的数值进行对数处理,但对y轴的数值我不知道怎么处理,因为在我的程序中并没有明确生成这些y值。
2 个回答
0
根据这个解决方案,我们可以定义一个简单的方法:
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')
plt.yscale('log')
然后可以这样调用它:
plot_loghist(data, 10)
这是我数据的一个输出示例:

28
可以查看pyplot的文档。
- 使用pyplot.hist时,可以通过设置参数log=True来让y轴使用对数刻度。
- pyplot.hist接受
bins
这个参数,但你需要自己把x轴设置为对数刻度。
举个例子:
#!/usr/bin/python
import numpy
from matplotlib import pyplot as plt
data = numpy.random.gumbel(2 ** 20, 2 ** 19, (1000, ))
bins = range(15, 25)
plt.xticks(bins, ["2^%s" % i for i in bins])
plt.hist(numpy.log2(data), log=True, bins=bins)
plt.show()
这样做会显示每个区间内实际有多少个元素,并且在对数坐标轴上绘制(这就是人们通常所说的对数图)。我不太确定你说的意思是想要这个,还是想要在普通坐标轴上绘制计数的对数值。
顺便说一下,区间的间隔不一定要均匀。