Search code examples
rggplot2shinyggplotly

ggplot legend options will not be adopted in ggplotly in shiny


I created a plot with ggplot2 and want to publish it in my Shiny App with plottly. Unfortunately the position of the legend is not adopted. Furthermore a 1 is added to every entry in the legend and the caption of the Plot disappears.

Part of my Plot

plot = ggplot() +
  geom_bar(data = pi_plot, aes(x = as.Date(Month), y = value, fill = Domain), position = "stack", stat = "identity") +
  geom_line(data = pi_fc_ly_plot, aes(x = as.Date(Month), y = value, group = PI, colour = PI), size = 0.75) +
  theme(legend.title = element_blank()) +
  labs(title = "Traffic",
       subtitle = "Visits", 
       y = "Pageviews", 
       x = "Month", 
       caption = "Source: Google Analytics") +
  scale_x_date(labels = date_format("%B"), 
               date_breaks = "month",
               expand = c(0, 0)) +
  scale_y_continuous(legend.position = "bottom") 

Call the Plot in the App

ggplotly(plot)

Solution

  • I did something similar some time ago. I specified my legend position as part of my ggplotly function call instead of my ggplot function call. You could try to amend your code as follows and see if it works

    plot = ggplot() +
      geom_bar(data = pi_plot, aes(x = as.Date(Month), y = value, fill = Domain), position = "stack", stat = "identity") +
      geom_line(data = pi_fc_ly_plot, aes(x = as.Date(Month), y = value, group = PI, colour = PI), size = 0.75) +
      theme(legend.title = element_blank()) +
      labs(title = "Traffic",
           subtitle = "Visits", 
           y = "Pageviews", 
           x = "Month", 
           caption = "Source: Google Analytics") +
      scale_x_date(labels = date_format("%B"), 
                   date_breaks = "month",
                   expand = c(0, 0))
    
     ggplotly(plot) %>% layout(legend = list(orientation = "h", y=-0.5))
    

    I don't know about the source of your caption issue.