我正在使用 pandas 制作一个相当简单的直方图
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()
如果我用 pandas 命令替换
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.
我确实得到了对数刻度直方图,但它只有条形的顶线,但没有垂直条形或颜色。我做了什么严重错误的事情还是这只是熊猫不支持?
从 Paul H 的代码中,我将
bottom=0.1
添加到 hist
调用修复了问题,我猜有某种被零除的东西,或者其他东西。
我建议在 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)
或者等效地,您可以直接使用数据框列(系列)的
plot
方法:
df["column_name"].plot(kind="hist", logy=True)
还有
logx
用于对 x 轴进行对数缩放,loglog=True
用于对两个轴进行对数缩放。
没有任何数据很难诊断。以下对我有用:
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')
这里的关键是将
ax
传递给直方图函数,并指定 bottom
,因为对数刻度上没有零值。
Jean PA 的解决方案是这个问题最简单、最正确的解决方案。由于我没有代表发表评论,因此将其写为答案。
为了直接从 pandas 构建直方图,一些参数无论如何都会传递给 matplotlib.hist 方法,所以:
results.val1.hist(bins = 120, log = True)
会生产你需要的东西。
添加一些额外的信息,你也可以使用
results.val1.hist(bins = 120, log = [True, True])
同时指定 x 轴和 y 轴。