简体   繁体   中英

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.)

在此处输入图像描述

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)

By mapping symbol and color argument to a factor variable you can create one trace per symbol and name. The following code may solve your problem:

col3 <- colorRamp(c("red", "blue"))
p = plot_ly(data,x = ~x, y = ~y)
add_markers(p, symbol = ~factor(symbol), 
            color = ~factor(name), 
            colors = col3, symbols = c(27,4))

Check this link for more details on scatter plot traces https://plotly-book.cpsievert.me/scatter-traces.html

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)

在此处输入图像描述

We can try symbols = I(c('27', '4')) for specifying symbols if we use a 2 level categorical variable for the symbols.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM