在 plotly 中明确设置箱线图的颜色

Explicitly set colours of the boxplot in ploltly

我正在使用 plotly express 绘制 boxplot,如下所示:

px.box(data_frame=df, 
       y="price", 
       x="products",
       points="all")

然而,产品的盒盆显示为相同的颜色。它们是四种产品。我想用不同的颜色给每个颜色着色,使用附加参数 color_discrete_sequence 不起作用。

我使用 plotly.express.data.tips() 作为示例数据集,并正在创建一个名为 mcolour 的新列来展示我们如何使用附加列进行着色。见下文;

## packages
import plotly.express as px
import numpy as np
import pandas as pd
## example dataset:
df = px.data.tips()

## creating a new column with colors
df['mcolour'] = np.where(
     df['day'] == "Sun" , 
    '#636EFA', 
     np.where(
        df['day'] == 'Sat', '#EF553B', '#00CC96'
     )
)
## plot
fig = px.box(df, x="day", y="total_bill", color="mcolour")
fig = fig.update_layout(showlegend=False)
fig.show()

因此,如您所见,您可以使用 plotly.express.box() 中的 color 参数根据另一列简单地分配颜色。

您需要在绘图之前添加此参数设置(作为有效解决方案的一部分),以便正确对齐(确实如此!)新着色的箱线图。

fig.update_layout(boxmode = "overlay")

boxmode 设置“overlay”使绘图恢复到正常布局,在设置颜色后似乎被覆盖(如设置“group”)。

在 plotly help 中提到了 boxmode:

"Determines how boxes at the same location coordinate are displayed on the graph. If 'group', the boxes are plotted next to one another centered around the shared location. If 'overlay', the boxes are plotted over one another [...]"

希望对您有所帮助! R