KBE11416
KBE11416

Reputation: 127

PlotlyR - Scatter Legend

I'm trying to show a legend in R plotly based on 3 levels.

cols <- c(Poor = "steelblue",
          Fair = "slateblue",
          Good = "grey45")

I have read multiple entries stating the column must be class factor. Even with that mutate "showlegend = T" does not display a legend. Is it possible do do this without adding all 3 markers separately?


plot_data <- plot_data %>% mutate(label_col = as.factor(label_col))
        
        p <-   plot_ly(data = plot_data,
                       x = ~r_score,
                       y = ~b_score,
                       type = "scatter",
                       marker = list( title = "Rating",
                                      size = ~plot_data$TTM_Units ,
                                      color = ~cols[plot_data$label_col],
                                      line = list(color = 'rgba(1, 0, 0, .8)',
                                                  width = 2),
                                      opacity = .5),
                                      showlegend = TRUE,
                                      inherit = TRUE)

Upvotes: 0

Views: 54

Answers (1)

stefan
stefan

Reputation: 125018

You could achieve your desired result by mapping a variable on the color attribute and setting you desired color palette via the colors argument.

Making use of the ggplot2::diamonds dataset as example data:

cols <- c(
  Poor = "steelblue",
  Fair = "slateblue",
  Good = "grey45"
)

library(plotly)

plot_data <- diamonds %>%
  filter(cut %in% names(cols))

plot_ly(
  data = plot_data,
  x = ~carat,
  y = ~price,
  color = ~cut,
  size = ~depth,
  type = "scatter",
  mode = "markers",
  colors = cols,
  marker = list(
    title = "Rating",
    line = list(
      color = "rgba(1, 0, 0, .8)",
      width = 2
    ),
    opacity = .5
  )
)
#> Warning: `line.width` does not currently support multiple values.

#> Warning: `line.width` does not currently support multiple values.

Upvotes: 1

Related Questions