0

I'm trying to see if I can insert 2 ggplot charts made in RStudio into a basic dashboard in RShiny. The desired output is a basic dashboard with 2 graphs on it, one below the other. Ideally I would have one code that produces the dashboard with the 2 graphs. The code ideally will run without user interaction so that it can automatically update.

What about saving each ggplot output (as a .pdf?) and then inserting the image into the dashboard?

I've looked at : Shiny building 2 graphs one below the other

There's apparently a way to combine graphs in ggplot but my output needs to be a dashboard: Side-by-side plots with ggplot2 First the basic dashboard code:

##DASHBOARD CODE


library(shinydashboard)

dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody()
)
##basic dashboard layout


library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody()
)

server <- function(input, output) { }

shinyApp(ui, server)
##viewing blank dashboard



library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Plasma Therapy"),
  dashboardSidebar(),
  dashboardBody(
    # Boxes need to be put in a row (or column)
    fluidRow(
      box(plotOutput("plot1", height = 250)),
      
      box(
        title = "Controls",
        sliderInput("slider", "Number of observations:", 1, 100, 50)
      )
    )
  )
)

server <- function(input, output) {
  set.seed(122)
  histdata <- rnorm(500)
  
  output$plot1 <- renderPlot({
    data <- ggplot(data=o2outcomes, aes(x=transfusion_date, y=ID, group=1)) +
      geom_line()+
      ylim(0, 100)+labs(y= "Number of Patients Transfused", x = "Transfusion Date")+ggtitle("Number of Patients Transfused Over Time") 
    ##create line graph 
    
  })
}

shinyApp(ui, server)

##formatting dashboard

setwd("/Users/k/Desktop/"COVID")
##set the working directory

library(readr)
library(dplyr)
library(ggplot2)
library(scales)
library(shiny)
library(grid)
library(tidyverse)
library(stringr)
library (lubridate)
library (tinytex)
install.packages("anytime")
install.packages("devtools")
library(devtools)
#load the packages needed


o2outcomes <- read.csv(
  file="patients_transfused.csv",
  stringsAsFactors = FALSE)

o2outcomes <- o2outcomes[!apply(is.na(o2outcomes) | o2outcomes == "", 1, all),]
##remove blank and NA data

view (o2outcomes)

(names(o2outcomes)[10] <- "transfusion_date")
##rename column 8 for transferring from 'character' to 'date'


o2outcomes <- transform(o2outcomes,
                        td = anytime::anytime(gsub("/20 ","/2020 ",transfusion_date))
)

o2outcomes$transfusion_date <- parse_date_time(o2outcomes$transfusion_date,
                                               orders = "%m/%d/%y %H%M")
##convert data from character into date


o2outcomes <- o2outcomes[order(o2outcomes$transfusion_date),]
##sort by date


o2outcomes <- o2outcomes[order(o2outcomes$transfusion_date), ]
o2outcomes$ID <- seq_len(nrow(o2outcomes))
##create ID to track cumulative cases

ggplot(data=o2outcomes, aes(x=transfusion_date, y=ID, group=1)) +
  geom_line()+
  ylim(0, 100)+labs(y= "Number of Patients Transfused", x = "Transfusion Date")+ggtitle("Number of Patients Transfused Over Time") 
##create line graph 

setwd("/Users/k/Desktop/COVID")
##set the working directory


library(dplyr)
library(ggplot2)
library(tidyr)
##these are the packages you would need to generate figure. This code loads the packages. 

cols<-c("AmbientAir"="lightblue","LowFlow"="blue","HighFlow"="orange","NIPPV"="purple","MechanicalVentilation"="red","ECMO"="black")
##this is setting the colors

Figure<-read.csv("Figure.csv",header=TRUE)
Figure_Event<-read.csv("Figure_Event.csv",header=TRUE)
##this loads your files

Figure_Event %>% filter(Event=="Discharged" | Event=="Death") %>% filter(Patient<26)-> Figure_Event
##this filters the Figure_Event file to relevent rows

Figure %>% drop_na(Requirement) %>% ggplot() + geom_line(aes(x=Day,y=Patient,group=Patient,col=Requirement),lwd=2.5) + scale_color_manual(values=cols) + scale_y_continuous(trans="reverse",breaks=seq(1,50,1))+scale_x_continuous(breaks=seq(-14,24,1))+theme(panel.grid.major = element_blank(),panel.grid.minor = element_blank(),panel.background = element_blank()) + geom_vline(xintercept=0) + geom_point(data=Figure_Event, aes(x=Day,y=Patient,shape=Event),size=4) + scale_shape_manual(values=c(15,22)) + scale_color_discrete(breaks=c("AmbientAir","LowFlow","HighFlow", "NIPPV","MechanicalVentilation","ECMO"))
##this makes the figure with the ggplot package and reorders the legend

Thanks

Phil
  • 7,287
  • 3
  • 36
  • 66
  • 2
    I there a reason why you would no call the r code that generates the graphs directly from your `server.r` script and have the calculations re-executed each time an instance of shiny is called? You can export as .png or .pdf and post, but it defeats the purpose of shiny, and it would be just as easy to build a simple html page for two images – sconfluentus May 19 '20 at 14:14
  • Unsure if this answers your question: the dashboard is expected to update each time it is loaded. The data will be continuously changing. I didn't quite understand the full question if there's a way to simplify it for a beginner that would help thanks – htxepidemiologist May 19 '20 at 14:20
  • 2
    If the data is continuously updating, then you want shiny to re-draw the graph every time someone calls it, so you get the freshest chart. There is no reason to run a script in rStudio, the server is able to source your data and create the ggplot directly, no middle man, and the push it to the ui. – sconfluentus May 19 '20 at 14:34
  • 1
    (1) *"saving each ggplot output (as a .pdf?) and then inserting the image"*, strongly recommend against this, it defeats a great feature of `shiny`. (2) *"combine graphs in ggplot"*, this is often more pain than its worth. Combining plots is generally fine, but you do lose a little bit of control on some parts (without more wrangling). Since you want two plots, "stacked", I would imagine just two `plotOutput` objects in `ui` and two `output$... <- renderPlot(...)` blocks. (3) *"automatically update"* ... reacting to user input, or periodically get new data? Look at `shiny::invalidateLater`. – r2evans May 19 '20 at 14:36
  • htxepidemiologist, the premise of two simple plots on a shiny page is about as fundamental in shiny as one can get, so perhaps I'm missing something in your question. You say two plots but have only one `plotOutput` in your code, so I'm not certain if you don't know how to deal with two plots or if there's another problem. Also, I'm not certain how your various code blocks work together. Can you provide a little more explanation? (Realize we can do nothing without sample data. Consider using `dput` or using a standard/public dataset.) – r2evans May 19 '20 at 14:39

0 Answers0