You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自定义Plotly 3D散点图的图例显示顺序?

解决Plotly 3D散点图Time图例顺序混乱问题

问题说明

生成3D散点图时,标记形状对应Treatment(IC、IT、YS),颜色对应Time(0、2、4、6、12、24、48、72),其余显示正常,但Time图例顺序不符合预期,希望调整为从0到72的顺序。推测是Time转为factor类型时顺序未指定导致,尝试过legendgroup = ~Time和traceorder = "normal"/"grouped"但无效。

原代码

# PCA Plot - 3D
pca_data_3D <- data.frame(Sample = rownames(pca$x),
                          PC1 = pca$x[,1],
                          PC2 = pca$x[,2],
                          PC3 = pca$x[,3],
                          Treatment = pca_data_2D$Treatment,   # already converted to factor
                          Time = pca_data_2D$Time)             # already converted to factor

treatment_groups <- c("YS" = "square", "IT" = "cross", "IC" = "circle")
time_groups <- c("0" = "#BC3C29", "2" = "#0072B5", "4" = "#E18727", "6" = "#20854E", 
                 "12" = "#7876B1", "24" = "#6F99AD", "48" = "#FFDC91", "72" = "#EE4C97")

hover_info <- pca_data_3D$Sample

pca_data_3D %>%
  plot_ly(
    type = "scatter3d", mode = "markers",
    x = ~PC1, y = ~PC2, z = ~PC3,
    symbol = ~Treatment, symbols = treatment_groups, 
    color = ~Time, colors = time_groups,
    hovertext = ~hover_info
  ) %>%
  layout(
    title = "PCA Graph PC1,2,3"
  )

解决方案

问题根源是Time因子的水平顺序未明确指定,Plotly会默认按因子水平的字母顺序生成图例,而非数值顺序。只需显式指定Time因子的水平顺序,再配合layout调整图例顺序即可:

  • 重新设置Time列的因子水平,确保顺序为0→2→4→6→12→24→48→72
  • 在layout中指定图例的traceorder为"normal"(按数据生成顺序显示)

修改后的代码:

# PCA Plot - 3D
pca_data_3D <- data.frame(Sample = rownames(pca$x),
                          PC1 = pca$x[,1],
                          PC2 = pca$x[,2],
                          PC3 = pca$x[,3],
                          Treatment = pca_data_2D$Treatment,
                          # 显式指定Time因子的水平顺序
                          Time = factor(pca_data_2D$Time, levels = c("0","2","4","6","12","24","48","72")))

treatment_groups <- c("YS" = "square", "IT" = "cross", "IC" = "circle")
time_groups <- c("0" = "#BC3C29", "2" = "#0072B5", "4" = "#E18727", "6" = "#20854E", 
                 "12" = "#7876B1", "24" = "#6F99AD", "48" = "#FFDC91", "72" = "#EE4C97")

hover_info <- pca_data_3D$Sample

pca_data_3D %>%
  plot_ly(
    type = "scatter3d", mode = "markers",
    x = ~PC1, y = ~PC2, z = ~PC3,
    symbol = ~Treatment, symbols = treatment_groups, 
    color = ~Time, colors = time_groups,
    hovertext = ~hover_info
  ) %>%
  layout(
    title = "PCA Graph PC1,2,3",
    # 指定图例按因子水平顺序显示
    legend = list(traceorder = "normal")
  )

关键说明

  • 显式指定因子水平是核心:当把数值转为factor时,R默认会按字符排序(比如"12"会排在"2"前面),必须手动指定levels参数来锁定顺序。
  • traceorder = "normal"确保图例按trace生成的顺序显示,而trace顺序由因子水平顺序决定,两者配合即可得到预期的图例顺序。

内容的提问来源于stack exchange,提问作者SIV0625TriX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 13:24:56