Skip to main content
 首页 » 编程设计

python之Plotly 箱形图关闭异常值检测

2024年11月24日9linjiqin

在 Plotly (Python) 中,箱形图默认检测离群值,如果有它确定为离群值的东西,则 mustache 不会扩展到离群值。但是,我知道我的所有数据点都不应该被视为异常值。是否可以关闭箱形图中的异常值检测,并将整个数据集视为异常值?

顺便说一句,我仍然想在箱形图旁边显示所有点,所以我不想使用选项 boxpoints=False 强制箱形图包括所有点数。

请您参考如下方法:

似乎目前唯一的方法是使用多个轨迹并将它们调整到相同的位置,如下图和片段所示。如果您需要一些详细信息,请查看末尾的片段和图表。

在下面的代码片段中,我使用 go.Box(x=x0) 来处理两个具有相同数据但标记和线条设置不同的不同迹线以实现此目的:

剧情:

代码:

# imports 
import plotly 
from plotly import tools 
import pandas as pd 
import numpy as np 
import plotly.graph_objs as go 
 
# setup 
np.random.seed(123) 
 
# data 
y0 = np.random.randn(50)-1 
x0 = y0 
x0 = [0 for y in y0] 
 
# include an outlier 
y0[-1] = 4 
 
# traces 
trace0 = go.Box(x=x0, 
                y=y0, boxpoints = False, pointpos = 0, 
                marker = dict(color = 'rgb(66, 167, 244)'), 
) 
 
trace1 = go.Box(x=x0, 
                y=y0, boxpoints = 'all', pointpos = 0, 
                marker = dict(color = 'rgb(66, 66, 244)'), 
                line = dict(color = 'rgba(0,0,0,0)'), 
                fillcolor = 'rgba(0,0,0,0)' 
) 
 
data=[trace0, trace1] 
 
# figure 
fig = go.Figure(data) 
fig.show() 

有关默认行为的详细信息:

如果未指定 Boxpoints,则这些线将不包括异常值:

plotly :默认

代码:

# imports 
import plotly 
from plotly import tools 
import pandas as pd 
import numpy as np 
import plotly.graph_objs as go 
 
# setup 
np.random.seed(123) 
 
# data 
y0 = np.random.randn(50)-1 
y0[-1] = 4 
 
# traces 
trace0 = go.Box(y=y0, pointpos = 0, 
                marker = dict(color = 'rgb(66, 167, 244)'), 
 
) 
 
# figure 
fig = go.Figure(trace0) 
fig.show() 

使线条包含离群值的唯一方法是通过设置 boxpoints = False 删除所有框点

剧情:


代码:

# imports 
import plotly 
from plotly import tools 
import pandas as pd 
import numpy as np 
import plotly.graph_objs as go 
 
# setup 
np.random.seed(123) 
 
# data 
y0 = np.random.randn(50)-1 
y0[-1] = 4 
 
# traces 
trace0 = go.Box(y=y0, pointpos = 0, 
                marker = dict(color = 'rgb(66, 167, 244)'), 
                boxpoints = False 
) 
 
# figure 
fig = go.Figure(trace0) 
fig.show() 

当然,这不是您的目标。

希望对您有所帮助。如果没有,请随时告诉我。