1
votes

So, i'm starting to use shiny and making interactive plots. So far, i've made my first and it looks like this: enter image description here

The code that i used for this plot was

ui <- fluidPage(titlePanel("Suicide Numbers Per 100k"),
                sidebarLayout(sidebarPanel(selectInput("region","Region",choices = unique(df$Country))),
                mainPanel(plotOutput("country100kplot"))))


server <- function(input,output){
  output$country100kplot <- renderPlot(df%>% filter(Country == input$region) %>% ggplot(aes(x=Year,y=Suicides_per_100k,colour=Generation))+geom_line()+labs(x="",y="Suicides",title = "")+theme(plot.title = element_text(hjust = 0.5)))
}

shinyApp(ui,server)

Here, im only using dpyr,ggplot2 and shiny packages. We have a line plot for each generation ( and the user can select the country ), but the plot can be very noisy as you can see.

Say i only want to see the "Boomer" generation line; i would unmark all the other generation to see only this line plot. How can i do that?

EDIT: I tried to use ggplotly. It worked well for general plots. But i don't know why, it doesn't appear on the Shiny. The ggplotly only appears in my R Viewer, and on the shiny, it shows the original ggplot2 plot: enter image description here

1
Try another more interactive library, like plotly. plotly.com/r/line-charts. This may also help in terms of how to integrate into Shiny. stackoverflow.com/questions/48017341/…Adam
Aww, there's no way to do it with ggplot2?Matheus Barreto Alves
You can convert a ggplot into a plotly object, but IMO it doesn't always look great. Maybe take a look at the package ggiraph. It builds on ggplot2 and I think it looks pretty slick. I am not experienced enough with it to put in an answer on it.Adam
Im having some issue. Check my editMatheus Barreto Alves
It may be that you need to use plotly::renderPlotly() instead of renderPlot(), but hard to say.Adam

1 Answers

0
votes

The reason why this won't appear in Shiny with your current code is that you need to use a separate wrapper for plotly objects. I do not have access to the data you used but here is how I would adjust your code in order for this to work.

Main thing to note is the use of plotlyOutput() in the UI and renderPlotly in the Server section.

library(shiny)
library(tidyverse)
library(plotly)

ui <- fluidPage(titlePanel("Suicide Numbers Per 100k"),
                sidebarLayout(sidebarPanel(selectInput("region","Region",choices = unique(df$Country))),
                              mainPanel(plotlyOutput("country100kplot"))))


server <- function(input,output){
  output$country100kplot <- renderPlotly({
    
  g <-  df%>% 
      filter(Country == input$region) %>% 
      ggplot(aes(x=Year,y=Suicides_per_100k,colour=Generation))+
      geom_line()+
      labs(x="",y="Suicides",title = "")+
      theme(plot.title = element_text(hjust = 0.5))
    
  g <- ggplotly(g)
    })
}

shinyApp(ui,server)