Obromios
Obromios

Reputation: 16383

How to manually add symbols with plotly in R

I have a plot_ly 3D scatter plot that uses three traces, and I want to use a different symbol and color for each trace. My code looks like this

library(plotrix)
library(plotly)
library(processx)

x <- c(1, 2, 3, 4)
y <- c(2, 4, 6, 8)
z <- c(1, 2, 3, 4)
df <- data.frame(x, y, z)
z1 <- z + 1.5
df1 <- data.frame(x, y, z1)
z2 <- z + 3
df2 <- data.frame(x, y, z2)
symbols <- c("circle", "diamond", 'triangle-down')
colors <- c("gray", "lightgray", "darkslategray")
plot<- plot_ly()%>%
  add_trace(data = df, x = ~x, y = ~y, z = ~z,type = "scatter3d",
    mode = 'markers', marker = list(size = 8, symbol = 1, symbols = symbols, color = 1, colors = colors)) %>%
  add_trace(data = df1, x = ~x, y = ~y, z = ~z1,type = "scatter3d",
            mode = 'markers', marker = list(size = 8, symbol = 2, symbols = symbols, color = 2, colors = colors)) %>%
  add_trace(data = df2, x = ~x, y = ~y, z = ~z2,type = "scatter3d",
            mode = 'markers', marker = list(size = 8, symbol = 8, symbols = symbols, color = 3, colors = colors)) %>%
  layout(title = 'Explore Options')
plot

which I would like to have the first trace to use circle markers, the second diamond and the third triangles, each with a different gray scale color, but instead I just get colored circles i.e. three traceas

Upvotes: 1

Views: 1733

Answers (1)

stefan
stefan

Reputation: 124268

One option would be to add a column to your dataframes which could then be mapped on the color and symbol attributes. Additionally I use named vectors of colors and symbols to assign colors and symbols to categories of the new column. Also note that colors and symbols should not to be placed inside the list for the marker specifications. Finally I simplified your code a bit.

The "triangle-down" symbol does not work, according to this reference, only ( "circle" | "circle-open" | "cross" | "diamond" | "diamond-open" | "square" | "square-open" | "x" ) are accepted.

library(plotly)

x <- c(1, 2, 3, 4)
y <- c(2, 4, 6, 8)
z <- c(1, 2, 3, 4)
df <- data.frame(x, y, z)
z1 <- z + 1.5
df1 <- data.frame(x, y, z = z1)
z2 <- z + 3
df2 <- data.frame(x, y, z = z2)

df$color <- "a"
df1$color <- "b"
df2$color <- "c"
symbols <- c("circle", "diamond", 'square')
colors <- c("gray", "lightgray", "darkslategray")
names(colors) <- names(symbols)  <- c("a", "b", "c")

plot<- plot_ly(x = ~x, y = ~y, z = ~z, color = ~color, symbol = ~color, colors = colors, symbols = symbols, marker = list(size = 8)) %>%
  add_trace(data = df, type = "scatter3d", mode = 'markers') %>%
  add_trace(data = df1, type = "scatter3d", mode = 'markers') %>%
  add_trace(data = df2, type = "scatter3d", mode = 'markers') %>%
  layout(title = 'Explore Options')
plot

enter image description here

Upvotes: 1

Related Questions