如何 select Plotly 中的箱线图颜色用于沿 x 轴的各个图?

How to select a boxplot color in Plotly for individual plots along the x axis?

我目前在 Plotly Express 中创建了一个 BoxPlot,如下所示

使用代码:

import plotly.express as px

fig = px.box(df, x="issuer.operator.name", y="validity_period", points='all', log_y=True,
            width=2000, height=1000,
            template="simple_white")
                
fig.show()

但是,我正在尝试创建图表,以便根据 x 轴对象(即 Internet Sec Research Group 为蓝色,Sectigo 为红色等)以不同颜色显示每个箱形图。

我从 post 得知您可以使用参数 color= '<column heading>' 来选择图表的颜色。从文档中,参数颜色是

Either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used to assign color to marks.

但是,当我尝试 运行 带有附加颜色参数的代码时

import plotly.express as px

    fig = px.box(df, x="issuer.operator.name", y="validity_period", color="issuer.operator.name", points='all', log_y=True,
                width=2000, height=1000,
                template="simple_white")
                    
    fig.show()

我收到以下错误:

KeyError: (nan, '', '', '')

我将如何更改每个箱线图的颜色?感谢任何帮助。

  • 已经模拟了你的数据框
  • 这在 issuer.operator.name
  • 中有 NaNs 的地方按您的要求工作
  • 模拟了一个NaN,然后得到同样的错误。由 dropna()
  • 解决
import plotly.express as px
import pandas as pd
import numpy as np
import random

df = pd.DataFrame({"issuer.operator.name":np.random.choice(["Internet Research", "Sectigo"],200),
                  "validity_period":np.random.uniform(1,100,200)*np.random.uniform(.001,1,200)})
df.iloc[random.randint(0,len(df)-1), 0] = np.nan
fig = px.box(df.dropna(), x="issuer.operator.name", y="validity_period", color="issuer.operator.name", points='all', log_y=True,
            width=700, height=1000,
            template="simple_white")
                
fig.show()