Why is ggplot scale_manual not correctly rendered in ggplotly?

28 Views Asked by At

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

There are 1 best solutions below

1
stefan On BEST ANSWER

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