使用Matplotlib

时间:2017-12-16 21:41:13

标签: python pandas numpy matplotlib statistics

我有一个pandas DataFrame,它在Series

中具有以下值
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,并指定绘图应该是内联的。

3 个答案:

答案 0 :(得分:17)

bins=8调用中指定hist表示最小值和最大值之间的范围平均分为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()

enter image description here

答案 1 :(得分:6)

  

使用x的日志绘制另一个直方图。

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

np.log(x).plot.hist(bins=8)
plt.show()

hist

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

这与绘制对数刻度不同,我们保持x相同,但改变水平轴的标记方式(向右挤压条形,向左侧拉伸)。

答案 2 :(得分:1)

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

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)

example hist plot