使用matplotlib在CDF直方图结束时的垂直线

Sam*_*ton 10 python matplotlib pandas

我正在尝试创建CDF,但在图表的末尾,有一条垂直线,如下所示:

情节

我已经读过他是因为matplotlib使用bin的末尾来绘制垂直线,这是有意义的,所以我在我的代码中添加了:

bins = sorted(X) + [np.inf]
Run Code Online (Sandbox Code Playgroud)

其中X是我正在使用的数据集,并在绘图时将bin大小设置为:

plt.hist(X, bins = bins, cumulative = True, histtype = 'step', color = 'b')
Run Code Online (Sandbox Code Playgroud)

这确实会删除末尾的行并产生所需的效果,但是当我对此图表进行规范化时,它会产生错误:

ymin = max(ymin*0.9, minimum) if not input_empty else minimum

UnboundLocalError: local variable 'ymin' referenced before assignment
Run Code Online (Sandbox Code Playgroud)

无论如何要用数据标准化数据

bins = sorted(X) + [np.inf]
Run Code Online (Sandbox Code Playgroud)

在我的代码中还是有另一种方法来删除图表上的行?

Ang*_*ams 9

绘制CDF的另一种方法如下(在我的例子中,X是从单位法线中抽取的一堆样本):

import numpy as np
import matplotlib.pyplot as plt

X = np.random.randn(10000)
n = np.arange(1,len(X)+1) / np.float(len(X))
Xs = np.sort(X)
fig, ax = plt.subplots()
ax.step(Xs,n) 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Zer*_*rin 5

我需要一种解决方案,无需更改其余代码(使用plt.hist(...)或与pandas一起使用dataframe.plot.hist(...)),并且可以在同一jupyter笔记本中轻松地多次重用。

我现在使用这个小辅助函数来做到这一点:

def fix_hist_step_vertical_line_at_end(ax):
    axpolygons = [poly for poly in ax.get_children() if isinstance(poly, mpl.patches.Polygon)]
    for poly in axpolygons:
        poly.set_xy(poly.get_xy()[:-1])
Run Code Online (Sandbox Code Playgroud)

可以这样使用(没有熊猫):

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

X = np.sort(np.random.randn(1000))

fig, ax = plt.subplots()
plt.hist(X, bins=100, cumulative=True, density=True, histtype='step')

fix_hist_step_vertical_line_at_end(ax)
Run Code Online (Sandbox Code Playgroud)

或者像这样(与熊猫一起):

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

df = pd.DataFrame(np.random.randn(1000))

fig, ax = plt.subplots()
ax = df.plot.hist(ax=ax, bins=100, cumulative=True, density=True, histtype='step', legend=False)

fix_hist_step_vertical_line_at_end(ax)
Run Code Online (Sandbox Code Playgroud)

结果

即使在同一轴上有多个累积密度直方图,此方法也能很好地工作。

警告:如果您的轴上包含其他mpl.patches.Polygon类别的面片,则可能不会导致所需的结果。那不是我的情况,所以我更喜欢在情节中使用这个小辅助函数。