Python 使用matplotlib在CDF直方图末尾的垂直线
我试图创建一个CDF,但在图的末尾,有一条垂直线,如下所示: 我读过他的文章,因为matplotlib使用箱子的末端来绘制垂直线,这很有意义,所以我在代码中添加了以下内容:Python 使用matplotlib在CDF直方图末尾的垂直线,python,pandas,matplotlib,Python,Pandas,Matplotlib,我试图创建一个CDF,但在图的末尾,有一条垂直线,如下所示: 我读过他的文章,因为matplotlib使用箱子的末端来绘制垂直线,这很有意义,所以我在代码中添加了以下内容: bins = sorted(X) + [np.inf] 其中X是我正在使用的数据集,并在打印时将bin大小设置为: plt.hist(X, bins = bins, cumulative = True, histtype = 'step', color = 'b') 这确实会删除末尾的线条并产生所需的效果,但是,当我现
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]
在我的代码中,还是有其他方法可以删除图形上的线?绘制CDF的替代方法如下(在我的示例中,
X
是从单位法线中提取的一组样本):
我需要一个解决方案,不需要修改其余代码(使用
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])
可以这样使用(没有熊猫):
或者像这样(和熊猫一起):
即使在同一轴上有多个累积密度直方图,这也很有效
警告:如果轴包含属于
mpl.patches.Polygon
类别的其他面片,则这可能不会产生所需的结果。这不是我的情况,所以我更喜欢在我的绘图中使用这个小辅助函数。假设您的意图是纯粹的美学,添加一条与绘图背景颜色相同的垂直线:
ax.axvline(x = value, color = 'white', linewidth = 2)
其中“value”代表最右边箱子的最右边。不知道为什么会被否决。这是hist+步骤工作原理的产物。您最好先计算累积直方图,然后使用
ax.step
。您想要CDF还是直方图?如果是CDF,那是哪一个?这是一个绝妙而美丽的选择!出现的问题是,绘图将在点之间进行线性插值,但真正的累积函数应该有这些“跳跃”。是的,这可能是一个公平的点-尽管它不会对大样本数据产生太大的差异。尽管如此,我还是更新了我的答案,改为使用plt.step
。谢谢谢谢这对我很管用。我有一个互补的CDF,所以我只需要将poly.set_xy(poly.get_xy()[:-1])
更改为poly.set_xy(poly.get_xy()[1:])
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)
ax.axvline(x = value, color = 'white', linewidth = 2)