python plotly graph_objects框标记的属性outliercolor不起作用(可能存在错误)

2024-09-27 21:29:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想我在类plotly.graph\u objects.box Marker中发现了一个bug,因为属性outliercolor不起作用。我遵循了https://plotly.github.io/plotly.py-docs/generated/plotly.graph_objects.Box.html#plotly.graph_objects.box.Marker.outliercolor中的引用,但是更改异常值的颜色没有任何区别

以下是一个例子:

import numpy as np
import pandas as pd
import plotly.graph_objects as go
from matplotlib.colors import LinearSegmentedColormap, to_hex

df_plot = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
cat_var = "species"
num_var = "petal_length"

lvls = df_plot[cat_var].unique()
n_levels = len(lvls)
cmap = LinearSegmentedColormap.from_list("my_palette", ["#111539", "#97A1D9"])
my_palette = [to_hex(j) for j in  [cmap(i/n_levels) for i in np.array(range(n_levels))]]

boxes = []
for l in range(n_levels):
    boxes += [
        go.Box(
            name = lvls[l],
            y = df_plot.loc[df_plot.loc[:, cat_var] == lvls[l], num_var].values,
            width = 0.4,
            boxpoints = "outliers",
            marker = {
                "outliercolor": "red", ### there may be a plotly.go bug here
                "color": my_palette[l],
                "size": 30,
                "opacity": 0.5
            }
        )
    ]
fig = go.Figure(data = boxes)
fig.update_layout(
    font = dict(
        size = 18
    ),
    showlegend = False,
    plot_bgcolor = "white",
    hoverlabel = dict(
        font_size = 18,
        font_family = "Rockwell"
    )
)
fig.show()


Tags: importgodfobjectsplotvarmyas
1条回答
网友
1楼 · 发布于 2024-09-27 21:29:05

这确实似乎是Plotly中的一个bug-可以作为bug报告提交给Plotly团队

值得注意的是,将boxpoints = "outliers"修改为boxpoints = "suspectedoutliers"会产生具有不同颜色的标记,因此suspectedoutliers的行为符合预期。但是,不能使用suspectedoutliers代替outliers,因为可疑异常值只是所有异常值的子集

您可以通过手动绘制异常值来实现所需的行为。要做到这一点,您仍然需要设置boxpoints=outliers,但随后在Plotly生成的异常值上以所需颜色将异常值绘制为单个散点

这有点复杂,因为这需要重写算法,以便在Plotly库执行此计算时准确地确定异常值。不幸的是,您无法从go.Box或Plotly以任何方式as these computations are performed by the Javascript under the hood when the figure renders提取Q1、Q3或其他统计信息

首先要注意的是,计算Q1和Q3在不同的Python库之间是不同的:在documentation中绘出了它们的方法,解释了它们使用Method #10 in this short paper来计算百分位数

在Python中,使用方法#10(线性插值)计算百分位数的函数如下所示:

## calculate quartiles as outlined in the plotly documentation 
def get_percentile(data, p):
    data.sort()
    n = len(data)
    x = n*p + 0.5
    x1, x2 = floor(n*p), ceil(n*p)
    y1, y2 = data[x1-1], data[x2-1] # account for zero-indexing
    return y1 + ((x - x1) / (x2 - x1))*(y2 - y1)

现在要从数据集中提取离群值,需要对数据进行子集:任何低于(Q1-1.5*IQR)或高于(Q3+1.5*IQR)的数据,其中IQR=Q3-Q1被视为离群值

综上所述:

from math import floor, ceil
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from matplotlib.colors import LinearSegmentedColormap, to_hex

df_plot = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
cat_var = "species"
num_var = "petal_length"

lvls = df_plot[cat_var].unique()
n_levels = len(lvls)
cmap = LinearSegmentedColormap.from_list("my_palette", ["#111539", "#97A1D9"])
my_palette = [to_hex(j) for j in  [cmap(i/n_levels) for i in np.array(range(n_levels))]]

## calculate quartiles as outlined in the plotly documentation 
def get_percentile(data, p):
    data.sort()
    n = len(data)
    x = n*p + 0.5
    x1, x2 = floor(n*p), ceil(n*p)
    y1, y2 = data[x1-1], data[x2-1] # account for zero-indexing
    return y1 + ((x - x1) / (x2 - x1))*(y2 - y1)

def get_fences(data):
    q1, q3 = get_percentile(data, 0.25), get_percentile(data, 0.75)
    iqr = q3-q1
    return (q1 - (1.5*iqr), q3 + (1.5*iqr))

boxes = []
for l in range(n_levels):
    data = df_plot.loc[df_plot.loc[:, cat_var] == lvls[l], num_var].values
    outliers = data[(data < get_fences(data)[0]) | (data > get_fences(data)[1])]
    print(outliers)
    boxes += [
        go.Box(
            name = lvls[l],
            y = data,
            width = 0.4,
            boxpoints = "outliers",
            marker = {
                "outliercolor": "red", ### there may be a plotly.go bug here
                "color": my_palette[l],
                "size": 30,
                "opacity": 0.5
            }
        ),
        go.Scatter(
            x = [lvls[l]]*len("outliers"),
            y = outliers,
            mode = 'markers',
            marker=dict(color="red", size=28, opacity=0.5)
        )
    ]
fig = go.Figure(data = boxes)
fig.update_layout(
    font = dict(
        size = 18
    ),
    showlegend = False,
    plot_bgcolor = "white",
    hoverlabel = dict(
        font_size = 18,
        font_family = "Rockwell"
    )
)
fig.show()

enter image description here

为了检查我们的工作,您会注意到,手动添加的稍小的异常值与Plotly确定的异常值相匹配。(您可以使手动添加的异常值变大,以掩盖绘图仪生成的非所需颜色的异常值)

相关问题 更多 >

    热门问题