Search code examples
rplotlylegendsymbolsr-plotly

R Plotly: Change legend symbol


How do I change the default legend symbols in R plotly? In my example below, I would like both symbols to be dots in the legend. The legend entry for "A" should be a blue circle. (By default, Plotly uses the symbol of the first point for each category.)

enter image description here

library(plotly)

# generate example data
name  = rep("A", 100)
name[1:100%%6 == 0] = "B"
data = data.frame(x = 1:100, y = sin(1:100),
                  name = name,
                  symbol = c(2, rep(1, 50), 2, 2,2, 2, 2, 2, rep(1, 43)))



plot_ly(data)%>%
          add_markers(x = ~x, y = ~y, symbol = ~symbol,
                      symbols = c(27, 4),
                      mode = 'markers', split = ~name)

Solution

  • Ah, plotly has picked up the first entry of the symbol column to use in its legend.

    > head(data[data$name == 'A', ])
      x          y name symbol
    1 1  0.8414710    A      2  # The first value is 2
    2 2  0.9092974    A      1
    3 3  0.1411200    A      1
    4 4 -0.7568025    A      1
    5 5 -0.9589243    A      1
    7 7  0.6569866    A      1
    

    Whereas, in case of 'B', -

    > head(data[data$name == 'B', ])
        x          y name symbol
    6   6 -0.2794155    B      1  # The first value is 1
    12 12 -0.5365729    B      1
    18 18 -0.7509872    B      1
    24 24 -0.9055784    B      1
    30 30 -0.9880316    B      1
    36 36 -0.9917789    B      1
    

    If you sort your data by name and symbol, then the legend should be consistent.

    library(plotly)
    
    # generate example data
    name  = rep("A", 100)
    name[1:100%%6 == 0] = "B"
    data = data.frame(x = 1:100, y = sin(1:100),
                      name = name,
                      symbol = c(2, rep(1, 50), 2, 2,2, 2, 2, 2, rep(1, 43)))
    
    data <- data[with(data, order(symbol, name)), ]
    
    plot_ly(data)%>%
      add_markers(x = ~x, y = ~y, symbol = ~symbol, symbols = c(27, 4), 
                  mode = 'markers', split = ~name)
    

    enter image description here