Ggplotly is not always making a legend correctly for where there are points and lines

Hi All,

Ggplotly is not always making a legend correctly for where there are points and lines.

Sometimes it only makes the legend key based on either geom_point or geom_line, whichever is the first layer.

Below is an example where it doesn't work and then another example where it does work.

If anyone knows why this is, or has a way to make it always work, it'd be much appreciated.

Thanks!

library(dplyr)
library(ggplot2)
library(plotly)

#This doesn't work: the legend is based only on the first geom shape
plot_data <- iris %>% 
  as_tibble() %>%  
  janitor::clean_names() 

plot <- ggplot(data = plot_data, aes(petal_width, petal_length, col = species)) +
  geom_point() +
  geom_line()

plotly::ggplotly(plot, tooltip = "text")

#This does works: I don't know why
plot_data <- storms %>%
  mutate(status = stringr::str_to_sentence(status)) %>%
  group_by(year, status) %>%
  summarise(wind = round(mean(wind), 2))

plot <- ggplot(data = plot_data, aes(year, wind, col = status, group = status)) +
  geom_point() +
  geom_line()

plotly::ggplotly(plot, tooltip = "text")

Hm, a very strange behavior. My first thought was a missing group but that didn't change anything. However, it works when using geom_path() instead.

You can arrange your data by petal width and it results in the same plot:

plot_data <- iris %>% 
  as_tibble() %>%  
  janitor::clean_names() %>% 
  arrange(petal_width)

plot <- ggplot(data = plot_data, aes(petal_width, petal_length, col = species)) +
  geom_point() +
  geom_path()

plotly::ggplotly(plot, tooltip = "text")

Does not explain why this happens but you come up with the expected result.

1 Like

Thanks @Z3tt :slight_smile:

I've added this as an issue to github

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

Great, it indeed looks like an issue. Happy coding!