1

I am using ggplot scale_manual to extend legend items to include values absent in the data and it works. However, when I use ggploty to render it, it doesn't work. Is there a work around this?

lims <- c("4", "6", "8", "10")
cols <- c("4" = "blue", "6" = "darkgreen", "8" = "red", "10" = "orange")
labs <- c("4" = "four", "6" = "six", "8" = "eight", "10" = "ten")

p <- ggplot(mtcars, aes(mpg, wt)) +
  geom_point(aes(color = factor(cyl)))

q <- p + 
  scale_color_manual(name = "Cylinder", values = cols, labels = labs, limits = lims)

# This extends the legend items by including "ten".
q

# In this case, the added legend item "ten" is dropped.
ggplotly(q)

enter image description here

1 Answer 1

0

Haven't found an option to prevent the unused category from being dropped. But one way to achieve your desired result would be to use a invisible geom_point layer which maps the unused category on color and NA on x and/or y:

library(plotly)

p <- ggplot(mtcars, aes(mpg, wt)) +
  geom_point(
    aes(color = factor(cyl))
  ) +
  geom_point(
    data = data.frame(x = NA_real_, y = NA_real_),
    aes(x = x, y = y, color = factor(10))
  ) +
  scale_color_manual(
    name = "Cylinder",
    values = cols,
    labels = labs,
    limits = lims
  )

ggplotly()

1
  • Thank you @stefan. You answer worked even to add more legend items. Just need to extend the data frame in the second geom_point() to the number of items one would like to add. But, one more questions, is there away to retain the legend labels from ggplot to the ggplotly?
    – BTT
    Commented Mar 21 at 14:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.