R: How to customize the legend order for a 3D scatter plot in plotly?
1
1
Entering edit mode
7 months ago
SIV0625TriX ▴ 30

Hi,

I'm trying to generate a 3D scatter plot and the shapes of markers correspond to 'Treatment' (IC, IT, YS), whilst, the colors correspond to 'Time' (0, 2, 4, 6, 12, 24, 48, 72). Everything went well except the legend order was like: 0YS, 12IC, 12IT, 24IC, 24IT, 2IC, 2IT, ... This order would be confusing and I wand it to go in the order from 0 to 72. I guess this automatically generated legend order was caused as Time was converted from numeric to factor. However, I failed to find a good way to set the order manually. Could anyone help?

And here is the corresponding part of my code:

# 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"
  )

Any help will be appreciated!

I've tried to set legendgroup = ~Time and traceorder = "normal"/"grouped" (separately), but it didn't seem to work. Yet I'm not sure if I did these in the right way.

I attached the automatically generated legends below:

This is the automatically generated legends

R r plotly • 798 views
ADD COMMENT
0
Entering edit mode
ADD REPLY
2
Entering edit mode
7 months ago
SIV0625TriX ▴ 30

This specific case is solved at https://stackoverflow.com/a/78192853/23671314 by formatting the "Time" to fit in alphabetical order. However, if there are more general ways to customize the legend order manually plz share. Thank you!

ADD COMMENT

Login before adding your answer.

Traffic: 1452 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6