Home > OS >  Fit legend on a graph generated by a shiny app
Fit legend on a graph generated by a shiny app

Time:11-27

The code below works normally, I would just like to make a brief modification. Note that I have two tabPanel, Graph1 and Graph2. If you generate the graphs you will notice that they generate the same graph, but with changes regarding the graph limits and variable names, so far OK. However, I would like to make a modification to the Graph2 legend. As it is: The number is:, however, I would like to show The value is:. The legend for Graph2 would look like this:legend("topright", legend= paste('US$', round(m,1)),title=" The value is:",title.col = "black", cex = 1.2). However, how to leave it automatically in the code, that is, so that whenever I click on Graph2, the correct legend appears on the graph.

Executable code below:

library(shiny)
library(shinythemes)
library(dplyr)
library(tidyverse)
library(lubridate)
library(shinyWidgets)

function.test<-function(){
  
  df1 <- structure(
    list(date1= c("2021-06-26","2021-06-26","2021-06-26","2021-06-26"),
         date2 = c("2021-06-27","2021-07-01","2021-07-02","2021-07-03"),
         Category = c("ABC","ABC","ABC","ABC"),
         Week= c("Saturday","Wednesday","Thurday","Saturday"),
         DR1 = c(5,4,1,1),
         DR01 = c(8,4,1,0), DR02= c(7,4,2,0),DR03= c(6,9,5,0),
         DR04 = c(5,5,4,0),DR05 = c(5,5,4,0),DR06 = c(7,5,4,0),DR07 = c(2,5,4,0),DR08 = c(2,5,4,0)),
    class = "data.frame", row.names = c(NA, -4L))
  
  return(df1)
  
}

f1 <- function(df1, dmda, CategoryChosse, plot = FALSE, var1, var2, gnum=0) {
  
  x<-df1 %>% select(starts_with("DR0"))
  
  x<-cbind(df1, setNames(df1$DR1 - x, paste0(names(x), "_PV")))
  PV<-select(x, date2,Week, Category, DR1, ends_with("PV"))
  
  med<-PV %>%
    group_by(Category,Week) %>%
    summarize(across(ends_with("PV"), median))
  
  SPV<-df1%>%
    inner_join(med, by = c('Category', 'Week')) %>%
    mutate(across(matches("^DR0\\d $"), ~.x   
                    get(paste0(cur_column(), '_PV')),
                  .names = '{col}_{col}_PV')) %>%
    select(date1:Category, DR01_DR01_PV:last_col())
  
  SPV<-data.frame(SPV)
  
  mat1 <- df1 %>%
    filter(date2 == dmda, Category == CategoryChosse) %>%
    select(starts_with("DR0")) %>%
    pivot_longer(cols = everything()) %>%
    arrange(desc(row_number())) %>%
    mutate(cs = cumsum(value)) %>%
    filter(cs == 0) %>%
    pull(name)
  
  (dropnames <- paste0(mat1,"_",mat1, "_PV"))
  
  SPV <- SPV %>%
    filter(date2 == dmda, Category == CategoryChosse) %>%
    select(-any_of(dropnames))
  
  if(length(grep("DR0", names(SPV))) == 0) {
    SPV[head(mat1,10)] <- NA_real_
  }
  
  datas <-SPV %>%
    filter(date2 == ymd(dmda)) %>%
    group_by(Category) %>%
    summarize(across(starts_with("DR0"), sum)) %>%
    pivot_longer(cols= -Category, names_pattern = "DR0(. )", values_to = "val") %>%
    mutate(name = readr::parse_number(name))
  colnames(datas)[-1]<-c(var1,var2)
  datas$days <- datas[[as.name(var1)]]
  datas$numbers <- datas[[as.name(var2)]]
  
  datas <- datas %>% 
    group_by(Category) %>% 
    slice((as.Date(dmda) - min(as.Date(df1$date1) [
      df1$Category == first(Category)])):max(days) 1) %>%
    ungroup
  
  m<-df1 %>%
    group_by(Category,Week) %>%
    summarize(across(starts_with("DR1"), mean))
  
  m<-subset(m, Week == df1$Week[match(ymd(dmda), ymd(df1$date2))] & Category == CategoryChosse)$DR1
  
  if (nrow(datas)<=2){
  val<-as.numeric(m)
  }

  else{
    mod <- nls(numbers ~ b1*days^2 b2,start = list(b1 = 0,b2 = 0),data = datas, algorithm = "port")
    coef<-coef(mod)[2]
    val<-as.numeric(coef(mod)[2])
  }
  
  
  if(plot){
    
  maxrange <-  range(0, datas$numbers, na.rm = TRUE)
  maxrange[2] <- maxrange[2]   10 
  
  if (gnum) maxrange[2] <- maxrange[2]   40 
  max<-max(0, datas$days, na.rm = TRUE) 1
  limx = c(0,max)
  limy = c(0,maxrange[2])
  
  plot(numbers ~ days,  xlim= limx, ylim= limy, xlab = var1, ylab=var2,
  xaxs='i',data = datas,main = paste0(dmda, "-", CategoryChosse))

    if (nrow(datas)<=2){
      abline(h=m,lwd=2) 
      points(0, m, col = "red", pch = 19, cex = 2, xpd = TRUE)
      text(.1,m  .5, round(m,1), cex=1.1,pos=4,offset =1,col="black")
      legend("topright",  legend= round(m,1),title="The number is:",title.col = "black", cex = 1.2)
      #legend("topright",  legend= paste('US$', round(m,1)),title=" The value is:",title.col = "black", cex = 1.2)
    }

    else{
      new.data <- data.frame(days = with(datas, seq(min(days),max(days),len = 45)))
      new.data <- rbind(0, new.data)
      lines(new.data$days,predict(mod,newdata = new.data),lwd=2)
      points(0, coef, col="red",pch=19,cex = 2,xpd=TRUE)
      text(.99,coef   1,max(0, round(coef,1)), cex=1.1,pos=4,offset =1,col="black")
      legend("topright",legend= round(coef,1),title="The number is:",title.col = "black", cex = 1.2)
      #legend("topright",legend= paste('US$',round(coef,1)),title="The value is:",title.col = "black", cex = 1.2)
    }
    
  }
  
  return(val)

}


ui <- fluidPage(
  
  shiny::navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
                    br(),
                    tabPanel("",
                             sidebarLayout(
                               sidebarPanel(
                                 uiOutput("date"),
                                 uiOutput("mycode")),
                               
                               mainPanel(
                                 tabsetPanel(
                                 tabPanel("Graph1", plotOutput("graph",width = "100%", height = "600")),
                                 tabPanel("Graph2", plotOutput("graph2",width = "100%", height = "600"))
                               )
                             ))
  )))

server <- function(input, output,session) {
  
  data <- reactive(function.test())
  
  
  output$date <- renderUI({
    req(data())
    all_dates <- seq(as.Date('2021-01-01'), as.Date('2021-01-15'), by = "day")
    disabled <- as.Date(setdiff(all_dates, as.Date(data()$date2)), origin = "1970-01-01")
    dateInput(input = "date2", 
              label = h4("Choose"),
              min = min(data()$date2),
              max = max(data()$date2),
              value = NA,
              datesdisabled = disabled)
    
  })
  
  output$mycode <- renderUI({
    req(input$date2)
    df1 <- data()
    df2 <- df1[as.Date(df1$date2) %in% input$date2,]
    selectInput("code", label = h4("Category"),choices=unique(df2$Category))
  })
  
  output$graph <- renderPlot({
    req(input$date2,input$code)
    var1 = "Days"
    var2 = "Numbers"
    f1(data(),as.character(input$date2),as.character(input$code),var1,var2,plot=TRUE)
  })
  
  output$graph2 <- renderPlot({
    req(input$date2,input$code)
    var1 = "Reserv"
    var2 = "Weekdays"
    f1(data(),as.character(input$date2),as.character(input$code),var1,var2,1,plot=TRUE)
  })

}

shinyApp(ui = ui, server = server) 

CodePudding user response:

Try this

library(shiny)
library(shinythemes)
library(dplyr)
library(tidyverse)
library(lubridate)
library(shinyWidgets)

function.test<-function(){
  
  df1 <- structure(
    list(date1= c("2021-06-26","2021-06-26","2021-06-26","2021-06-26"),
         date2 = c("2021-06-27","2021-07-01","2021-07-02","2021-07-03"),
         Category = c("ABC","ABC","ABC","ABC"),
         Week= c("Saturday","Wednesday","Thurday","Saturday"),
         DR1 = c(5,4,1,1),
         DR01 = c(8,4,1,0), DR02= c(7,4,2,0),DR03= c(6,9,5,0),
         DR04 = c(5,5,4,0),DR05 = c(5,5,4,0),DR06 = c(7,5,4,0),DR07 = c(2,5,4,0),DR08 = c(2,5,4,0)),
    class = "data.frame", row.names = c(NA, -4L))
  
  return(df1)
  
}

f1 <- function(df1, dmda, CategoryChosse, plot = FALSE, var1, var2, gnum=0, graf=1) {
  
  x<-df1 %>% select(starts_with("DR0"))
  
  x<-cbind(df1, setNames(df1$DR1 - x, paste0(names(x), "_PV")))
  PV<-select(x, date2,Week, Category, DR1, ends_with("PV"))
  
  med<-PV %>%
    group_by(Category,Week) %>%
    dplyr::summarize(dplyr::across(ends_with("PV"), median))
  
  SPV<-df1%>%
    inner_join(med, by = c('Category', 'Week')) %>%
    mutate(across(matches("^DR0\\d $"), ~.x   
                    get(paste0(cur_column(), '_PV')),
                  .names = '{col}_{col}_PV')) %>%
    select(date1:Category, DR01_DR01_PV:last_col())
  
  SPV<-data.frame(SPV)
  
  mat1 <- df1 %>%
    dplyr::filter(date2 == dmda, Category == CategoryChosse) %>%
    select(starts_with("DR0")) %>%
    pivot_longer(cols = everything()) %>%
    arrange(desc(row_number())) %>%
    mutate(cs = cumsum(value)) %>%
    dplyr::filter(cs == 0) %>%
    pull(name)
  
  (dropnames <- paste0(mat1,"_",mat1, "_PV"))
  
  SPV <- SPV %>%
    filter(date2 == dmda, Category == CategoryChosse) %>%
    select(-any_of(dropnames))
  
  if(length(grep("DR0", names(SPV))) == 0) {
    SPV[head(mat1,10)] <- NA_real_
  }
  
  datas <-SPV %>%
    dplyr::filter(date2 == ymd(dmda)) %>%
    group_by(Category) %>%
    dplyr::summarize(dplyr::across(starts_with("DR0"), sum)) %>%
    pivot_longer(cols= -Category, names_pattern = "DR0(. )", values_to = "val") %>%
    mutate(name = readr::parse_number(name))
  colnames(datas)[-1]<-c(var1,var2)
  datas$days <- datas[[as.name(var1)]]
  datas$numbers <- datas[[as.name(var2)]]
  
  datas <- datas %>% 
    group_by(Category) %>% 
    slice((as.Date(dmda) - min(as.Date(df1$date1) [
      df1$Category == first(Category)])):max(days) 1) %>%
    ungroup
  
  m<-df1 %>%
    group_by(Category,Week) %>%
    dplyr::summarize(dplyr::across(starts_with("DR1"), mean))
  
  m<-subset(m, Week == df1$Week[match(ymd(dmda), ymd(df1$date2))] & Category == CategoryChosse)$DR1
  
  if (nrow(datas)<=2){
    val<-as.numeric(m)
  }
  
  else{
    mod <- nls(numbers ~ b1*days^2 b2,start = list(b1 = 0,b2 = 0),data = datas, algorithm = "port")
    coef<-coef(mod)[2]
    val<-as.numeric(coef(mod)[2])
  }
  
  
  if(plot){
    
    maxrange <-  range(0, datas$numbers, na.rm = TRUE)
    maxrange[2] <- maxrange[2]   10 
    
    if (gnum) maxrange[2] <- maxrange[2]   40 
    max<-max(0, datas$days, na.rm = TRUE) 1
    limx = c(0,max)
    limy = c(0,maxrange[2])
    if (graf==1){
      if (nrow(datas)<=2) leg = round(m,1) else leg = round(coef,1)
      titl = "The number is:"
    }else if (graf==2){
      if (nrow(datas)<=2) leg = paste('US$', round(m,1)) else leg = paste('US$',round(coef,1))
      titl = " The value is:"
    }
    
    plot(numbers ~ days,  xlim= limx, ylim= limy, xlab = var1, ylab=var2,
         xaxs='i',data = datas,main = paste0(dmda, "-", CategoryChosse))
      legend("topright",  legend= leg,title=titl,title.col = "black", cex = 1.2)
    
    if (nrow(datas)<=2){
      abline(h=m,lwd=2) 
      points(0, m, col = "red", pch = 19, cex = 2, xpd = TRUE)
      text(.1,m  .5, round(m,1), cex=1.1,pos=4,offset =1,col="black")
      #legend("topright",  legend= leg,title=titl,title.col = "black", cex = 1.2)
      #legend("topright",  legend= round(m,1),title="The number is:",title.col = "black", cex = 1.2)
      #legend("topright",  legend= paste('US$', round(m,1)),title=" The value is:",title.col = "black", cex = 1.2)
    }
    
    else{
      new.data <- data.frame(days = with(datas, seq(min(days),max(days),len = 45)))
      new.data <- rbind(0, new.data)
      lines(new.data$days,predict(mod,newdata = new.data),lwd=2)
      points(0, coef, col="red",pch=19,cex = 2,xpd=TRUE)
      text(.99,coef   1,max(0, round(coef,1)), cex=1.1,pos=4,offset =1,col="black")
      
      # legend("topright",legend= round(coef,1),title="The number is:",title.col = "black", cex = 1.2)
      #legend("topright",legend= paste('US$',round(coef,1)),title="The value is:",title.col = "black", cex = 1.2)
    }
    
  }
  
  return(val)
  
}


ui <- fluidPage(
  
  shiny::navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
                    br(),
                    tabPanel("",
                             sidebarLayout(
                               sidebarPanel(
                                 uiOutput("date"),
                                 uiOutput("mycode")),
                               
                               mainPanel(
                                 tabsetPanel(
                                   tabPanel("Graph1", plotOutput("graph",width = "100%", height = "600")),
                                   tabPanel("Graph2", plotOutput("graph2",width = "100%", height = "600"))
                                 )
                               ))
                    )))

server <- function(input, output,session) {
  
  data <- reactive(function.test())
  
  
  output$date <- renderUI({
    req(data())
    all_dates <- seq(as.Date('2021-01-01'), as.Date('2021-01-15'), by = "day")
    disabled <- as.Date(setdiff(all_dates, as.Date(data()$date2)), origin = "1970-01-01")
    dateInput(input = "date2", 
              label = h4("Choose"),
              min = min(data()$date2),
              max = max(data()$date2),
              value = NA,
              datesdisabled = disabled)
    
  })
  
  output$mycode <- renderUI({
    req(input$date2)
    df1 <- data()
    df2 <- df1[as.Date(df1$date2) %in% input$date2,]
    selectInput("code", label = h4("Category"),choices=unique(df2$Category))
  })
  
  output$graph <- renderPlot({
    req(input$date2,input$code)
    var1 = "Days"
    var2 = "Numbers"
    f1(data(),as.character(input$date2),as.character(input$code),var1,var2,plot=TRUE, graf=1)
  })
  
  output$graph2 <- renderPlot({
    req(input$date2,input$code)
    var1 = "Reserv"
    var2 = "Weekdays"
    f1(data(),as.character(input$date2),as.character(input$code),var1,var2,1,plot=TRUE, graf=2)
  })
  
}

shinyApp(ui = ui, server = server) 
  • Related