matplotlib:绘图时忽略异常值

新手上路,请多包涵

我正在绘制来自各种测试的一些数据。有时在测试中我碰巧有一个异常值(比如 0.1),而所有其他值都小三个数量级。

使用 matplotlib,我绘制了范围 [0, max_data_value]

我怎样才能只放大我的数据而不显示异常值,这会弄乱我的图中的 x 轴?

我应该简单地取 95 个百分位数并在 x 轴上有范围 [0, 95_percentile] 吗?

原文由 Ricky Robinson 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

没有针对异常值的单一“最佳”测试。理想情况下,您应该合并先验信息(例如“这个参数不应该超过 x 因为等等……”)。

大多数异常值测试使用中位数绝对偏差,而不是第 95 个百分位数或其他一些基于方差的度量。否则,计算出的方差/stddev 将被异常值严重扭曲。

这是一个实现更常见的离群值测试之一的函数。

 def is_outlier(points, thresh=3.5):
    """
    Returns a boolean array with True if points are outliers and False
    otherwise.

    Parameters:
    -----------
        points : An numobservations by numdimensions array of observations
        thresh : The modified z-score to use as a threshold. Observations with
            a modified z-score (based on the median absolute deviation) greater
            than this value will be classified as outliers.

    Returns:
    --------
        mask : A numobservations-length boolean array.

    References:
    ----------
        Boris Iglewicz and David Hoaglin (1993), "Volume 16: How to Detect and
        Handle Outliers", The ASQC Basic References in Quality Control:
        Statistical Techniques, Edward F. Mykytka, Ph.D., Editor.
    """
    if len(points.shape) == 1:
        points = points[:,None]
    median = np.median(points, axis=0)
    diff = np.sum((points - median)**2, axis=-1)
    diff = np.sqrt(diff)
    med_abs_deviation = np.median(diff)

    modified_z_score = 0.6745 * diff / med_abs_deviation

    return modified_z_score > thresh

作为使用它的示例,您将执行以下操作:

 import numpy as np
import matplotlib.pyplot as plt

# The function above... In my case it's in a local utilities module
from sci_utilities import is_outlier

# Generate some data
x = np.random.random(100)

# Append a few "bad" points
x = np.r_[x, -3, -10, 100]

# Keep only the "good" points
# "~" operates as a logical not operator on boolean numpy arrays
filtered = x[~is_outlier(x)]

# Plot the results
fig, (ax1, ax2) = plt.subplots(nrows=2)

ax1.hist(x)
ax1.set_title('Original')

ax2.hist(filtered)
ax2.set_title('Without Outliers')

plt.show()

在此处输入图像描述

原文由 Joe Kington 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您不介意拒绝 Joe 提到的异常值,并且这样做纯粹是出于审美原因,您可以设置绘图的 x 轴限制:

 plt.xlim(min_x_data_value,max_x_data_value)

其中的值是您希望显示的限制。

plt.ylim(min,max) 也可以在 y 轴上设置限制。

原文由 Jdog 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题