Python Panda 柱状图日志尺度

我做了一个相当简单的直方图

results.val1.hist(bins=120)

这很好,但是我真的想在 y 轴上有一个对数刻度,我通常(可能不正确)是这样做的:

fig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111)
plt.plot(np.random.rand(100))
ax.set_yscale('log')
plt.show()

如果我用“熊猫”命令替换 plt命令,那么我得到:

fig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111)
results.val1.hist(bins=120)
ax.set_yscale('log')
plt.show()

结果会产生许多相同错误的副本:

Jan  9 15:53:07 BLARG.local python[6917] <Error>: CGContextClosePath: no current point.

我确实得到了一个对数尺度的直方图,但它只有条形图的顶部线条,没有垂直的条形图或颜色。是做错了什么,还是熊猫不支持?

从保罗 H 的代码,我增加了 bottom=0.1hist调用修复的问题,我猜有一些除以零的东西,或东西。

70178 次浏览

没有任何数据很难诊断。以下对我有效:

import numpy as np
import matplotlib.pyplot as plt
import pandas
series = pandas.Series(np.random.normal(size=2000))
fig, ax = plt.subplots()
series.hist(ax=ax, bins=100, bottom=0.1)
ax.set_yscale('log')

enter image description here

这里的关键是将 ax传递给直方图函数,并指定 bottom,因为对数刻度上没有零值。

我建议在 pyplot hist 函数中使用 log=True参数:

设置步骤

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


df = pd.DataFrame({'column_name': np.random.normal(size=2000)})

使用 pyplot:

plt.hist(df['column_name'], log=True)

enter image description here

或者,您可以直接使用 dataframe 列(系列)的 plot方法:

df["column_name"].plot(kind="hist", logy=True)

还有用于 x 轴对日志进行缩放的 logx和用于两轴对日志进行缩放的 loglog=True

Jean PA 的解决方案是这个问题最简单、最正确的解决方案。写这个作为一个答案,因为我没有代表评论。

为了直接从熊猫构建直方图,一些参数会传递给 matplotlib.hist 方法,所以:

results.val1.hist(bins = 120, log = True)

会生产出你需要的东西。