ggplotly legends are not the same as ggplot

56 Views Asked by At

I know this has been asked multiple times before, but I still struggle to find a straightforward answer that works on reproducible cases. I basically want the legends of ggplotly to be the same as ggplot. I'm providing a repex here but I want the solution to be dynamic because I sometimes don't have multiple shape aesthetics and the number of horizontal lines is also dynamic.

library(pacman)
pacman::p_load(dplyr, ggplot2, plotly, shiny)
data <- iris %>% mutate(
  my_shape = sample(c(T, F), size = nrow(iris), replace = T)
)

new_data <- data.frame(
  type = c("a", "b", "c"),
  value = c(2, 3, 4)
)

g <- ggplot(data) + 
  geom_point(aes(x = Sepal.Length, y = Petal.Width, shape = my_shape, fill = Species)) + 
  geom_hline(data = new_data, aes(yintercept = value, linetype = type, color = type)) +
  scale_fill_manual(
    values = c(
      "setosa" = "olivedrab4",
      "versicolor" = "steelblue4",
      "virginica" = "red"
    )
  ) +
  scale_shape_manual(values = c("TRUE" = 24, 'FALSE' = 21)) +
  guides(fill = guide_legend(override.aes = list(shape = 21)))

plot(g)

g

ggplotly(g)

ggplotly(g)

0

There are 0 best solutions below