Search code examples
rlegendr-plotly

Display color legend when data has only one category


I just found out that if a variable is mapped to the color argument in plotly, the legend is automatically displayed only if the variable has more than one category. This is illustrated below. df1 has two categories and they are displayed in the legend . df2, on the other hand, has only one category and no legend is displayed. My goal is to display the legend in the df2 plot.

library(plotly)

df1 <- data.frame(
  x = 1:100,
  y = rnorm(100),
  category = sample(c("cat", "dog"), 100, replace = TRUE)
)

plot_ly(
  type = "scatter",
  mode = "markers",
  data = df1,
  x = ~x,
  y = ~y,
  color = ~category
)

plotly with legend

f2 <- data.frame(
   x = 1:100,
   y = rnorm(100),
   category = "dog"
)

plot_ly(
  type = "scatter",
  mode = "markers",
  data = df2,
  x = ~x,
  y = ~y,
  color = ~category
)

plotly without legend


Solution

  • You can add a legend with the argument showlegend:

    plot_ly(
      type = "scatter",
      mode = "markers",
      data = df2,
      x = ~x,
      y = ~y,
      color = ~category
    ) %>% layout(showlegend = TRUE)
    

    enter image description here