2

I'm currently making a Shiny app and I tried to use this graph (this is used in the server):

  output$COTY_out1 <- renderPlot({
  
  data %>%
    group_by(year) %>%
    summarize(mean_ls = mean(life_satisfaction, na.rm = TRUE)) %>%
    ggplot(mapping = aes(x = year, y = mean_ls)) +
    geom_line() +
    geom_smooth() +
    labs(y = "Mean Life Satisfaction", x = "Year", title = "World")
  
})

This shows up well in the app!

enter image description here

Now, I tried to integrate plotly in this and basically copied this code from working apps. I also consulted stack and found similar answers.

  output$COTY_out1 <- renderPlotly({

p <- data %>%
  group_by(year) %>%
  summarize(mean_ls = mean(life_satisfaction, na.rm = TRUE)) %>%
  ggplot(mapping = aes(x = year, y = mean_ls)) +
  geom_line() +
  geom_smooth() +
  labs(y = "Mean Life Satisfaction", x = "Year", title = "World")

p <- ggplotly(p)
p
        
})

However, after doing this, the graph does not show up. Is there something wrong in the way I've integrated the ggplotly? Like I said before, I looked at similar answers on this forum and basically tried to copy paste a lot of them to no avail.

BoyAcc
  • 193
  • 7
  • 1
    Just call `ggplotly` with `last_plot()`? You may need to use `print` perhaps as I remember this is required sometimes in `shiny`. – NelsonGon Dec 19 '21 at 22:28
  • I'm a little confused, are you suggesting that rather than renaming my ggplot as `p` I instead write the plot as it is and then do `ggplotly(last_plot())`? Sorry I'm new to shiny. – BoyAcc Dec 19 '21 at 22:41
  • 1
    Yes but that may be disadvantagous depending on what the last plot is or you can just pipe the ggplot call into `ggplotly()` – NelsonGon Dec 19 '21 at 22:46
  • 1
    Your code looks fine. But without a [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) one can only guess. How do you add the plotly chart in the UI? Have you used `plotlyOutput`? – stefan Dec 19 '21 at 23:09

1 Answers1

3

I ended up finding the solution with some experimentation!

  output$COTY_out1 <- renderPlotly({

data %>%
    group_by(year) %>%
    summarize(mean_ls = mean(life_satisfaction, na.rm = TRUE)) %>%
    ggplot(mapping = aes(x = year, y = mean_ls)) +
    geom_line() +
    geom_smooth() +
    labs(y = "Mean Life Satisfaction", x = "Year", title = "World")
  
})

make sure you use plotlyOutput in the UI!

BoyAcc
  • 193
  • 7