【问题标题】:Vertical line at the end of a CDF histogram using matplotlib使用 matplotlib 的 CDF 直方图末尾的垂直线
【发布时间】:2017-02-05 07:48:15
【问题描述】:

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

我读到他是因为 matplotlib 使用 bin 的末端来绘制垂直线,这是有道理的,所以我在代码中添加了:

bins = sorted(X) + [np.inf]

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

plt.hist(X, bins = bins, cumulative = True, histtype = 'step', color = 'b')

这确实会删除最后的线并产生所需的效果,但是当我现在规范化此图时会产生错误:

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

UnboundLocalError: local variable 'ymin' referenced before assignment

有没有办法用

规范化数据
bins = sorted(X) + [np.inf]

在我的代码中还是有其他方法可以删除图表上的线条?

【问题讨论】:

  • 不知道为什么这被否决了。这是 hist + step 如何工作的神器。您最好计算累积直方图,然后使用ax.step
  • 您想要 CDF 还是直方图?如果是 CDF,是哪一个?

标签: python pandas matplotlib


【解决方案1】:

另一种绘制 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) 

【讨论】:

  • 这是一个绝妙而美丽的选择!
  • 出现的问题是绘图会在点之间进行线性插值,但真正的累积函数应该有这些“跳跃”。
  • 是的,这可能是一个公平的观点——尽管它对大量数据样本没有太大影响。尽管如此,我已经更新了我的答案,改为使用plt.step。谢谢!
【解决方案2】:

我需要一个解决方案,我不需要更改我的其余代码(使用 plt.hist(...) 或使用 pandas,dataframe.plot.hist(...))并且我可以在同一个 jupyter notebook 中轻松重复使用多次。

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

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])

可以这样使用(不用pandas):

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)

或者像这样(使用熊猫):

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)

即使您在同一轴上有多个累积密度直方图,这也很有效。

警告:如果您的坐标区包含属于mpl.patches.Polygon 类别的其他补丁,这可能不会导致想要的结果。那不是我的情况,所以我更喜欢在我的情节中使用这个小辅助函数。

【讨论】:

  • 谢谢!这对我有用。我有一个互补的 CDF,所以我只需要将 poly.set_xy(poly.get_xy()[:-1]) 更改为 poly.set_xy(poly.get_xy()[1:])
【解决方案3】:

假设你的意图是纯粹的审美,添加一条垂直线,与你的情节背景颜色相同:

ax.axvline(x = value, color = 'white', linewidth = 2)

其中“value”代表最右边 bin 的最右端。

【讨论】:

    猜你喜欢
    • 2014-04-15
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 2013-09-30
    • 2021-05-10
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    相关资源
    最近更新 更多