блестящее приложение: gpplot, основанный на условии, оси x даты и valueBoxOutput, не отображается - PullRequest
0 голосов
/ 20 марта 2020

Мой фрейм данных df:

  df<- structure(list(Dead = c(0L, 0L, 0L, 0L, 0L, 1L, 9L, 0L, 0L, 0L
  ), Case = c(120L, 70L, 50L, 40L, 39L, 20L, 18L, 13L, 9L, 2L), Recovered = c(30L,0L, 18L, 13L, 19L, 
  10L, 0L,16L, 0L, 1L), Critical = c(0L, 0L, 0L,                                                                                                                               
  0L, 8L, 4L, 0L, 3L, 2L, 0L), Date = c("18/03/2020", "17/03/2020",                                                                                                                                                                    
  "16/03/2020", "15/03/2020", "14/03/2020", "13/03/2020", "12/03/2020",                                                                                                                                                                    
  "11/03/2020", "10/03/2020", "09/03/2020")), class = "data.frame", row.names = c(NA,                                                                                                                                                                                                                                                    
  10L))

мой MWE:

library(shiny)
library(plotly)
library(ggplot2)
df$Date = as.Date(df$Date, format = "%d/%m/%Y")
ui <- fluidPage(
 title = 'testing',
 sidebarLayout(
   sidebarPanel(
   helpText(),
   selectInput("x", "Choose X-axis data", choices = names(df), selected = "Date"),
   selectInput("y", "Choose Y-axis data", choices = names(df)),
  # Input: Slider for the number of observations to generate ----
  sliderInput("n",
              "No. of bins:",
              value = 5,
              min = 1,
              max = 15) ,
   ),
 mainPanel(
   tabsetPanel(
     tabPanel("ggplot", plotlyOutput("regPlot1")),
     tabPanel("default plot", plotOutput("regPlot2")),
     tabPanel("Histogram", plotOutput("regPlot3"))
   ),
  fluidRow(
    shinydashboard::valueBoxOutput("totalCases",width = 2)
    )
   )
  )
 )

server <- function(input, output, session) {
 #calculation for box values
 total.cases <- sum(df$Case)
  ## Value1: Total cases ## 
  output$totalCases <- renderValueBox({
  shinydashboard::valueBox(
  formatC(total.cases, format="d", big.mark=','),
  paste('Total Cases:',total.cases),
  icon = icon("stats",lib='glyphicon'),
  color = "purple")
  })
    Graphcase <- reactive({
     Gchoice<-input$x
    })
 myData <- reactive({
   df[, c(input$x, input$y)]
 })
 #plot
  output$regPlot1 <- renderPlotly({
   # comment the if and else(block) to make run the code
   if(Graphcase=="Date"){

       ggplotly(ggplot(data = myData(), 
                aes_string(x = input$x, y = input$y)) +
                geom_line( color="blue") +
                geom_point(shape=21, color="black", fill="gray", size=4) +
                theme(axis.text.x = element_text(color="#993333", 
                                            size=10, angle=45,hjust = 1),
                 axis.text.y = element_text(color="#993333", 
                                            size=10, angle=45,hjust = 1)))
                     +scale_x_date(date_labels = "%b/%d")

    }else{
         ggplotly(ggplot(data = myData(), 
                  aes_string(x = input$x, y = input$y)) +
                  geom_line( color="blue") +
                 geom_point(shape=21, color="black", fill="gray", size=4) +
                 theme(axis.text.x = element_text(color="#993333", 
                                              size=10, angle=45,hjust = 1),
                   axis.text.y = element_text(color="#993333", 
                                              size=10, angle=45,hjust = 1)))

     }
   })

    # plot2
    output$regPlot2 <- renderPlot({
       par(mar = c(4, 4, .1, .1)) # margin lines
       plot(myData(), data = df)
    })
    #plot 3
     output$regPlot3 <- renderPlotly({
             ggplotly(ggplot(data = myData(), aes_string(x = input$x)) +
             geom_histogram(color="black", 
                            fill="blue",
                            binwidth=input$n)
      )
    })




     }

       shinyApp(ui, server)

Мой вопрос состоит из 3 частей:

1) Если вы запустите код и наведите курсор мыши на На графике точек вы заметите, что ggplot не показывает правильную дату на оси X. Я поставил +scale_x_date(date_labels = "%b/%d"), который решает проблему, однако он разбивает график для других данных. Другими словами, если я изменю ось X на любую другую переменную данных, она не будет отображаться правильно. После поиска я обнаружил, что использование if statements решит проблему. Поэтому я хочу поставить условие следующим образом: если ось x равна Date, график будет иметь масштаб_x_date (..). Если нет, я буду использовать тот же код в примере, и это условие будет применено также для оси Y, если выбрана дата. Я добавил график 2 «график по умолчанию», чтобы показать, что нормальная функция графика работает нормально даже с датой. Я попробовал условие в коде, и я получаю ошибки.

2) Я изо всех сил пытаюсь показать окно, так как вы можете видеть код, показывающий значения, даже icom, но без окна. Я использовал пространство имен, основанное на предположении, без надежды. ИМХО, я думаю, что это связано с пакетами, так как я замечаю предупреждения, некоторые пакеты маскируют команды.!

3) Дата, поскольку данные не могут использоваться для вычисления гистограммы. Возможно ли, что при открытии вкладки «Гистограмма» вместо двух отображается только одно поле ввода, т. Е. Ввод $ x и дата выпадающего списка исключаются?

Любые предложения.

1 Ответ

1 голос
/ 20 марта 2020

Для дальнейшего использования не задавайте несколько вопросов в одном посте. StackOverflow не только здесь, чтобы помочь вам, но и помогает другим людям, которые ищут ответ на проблему в своем коде. Нелегко понять, полезны ли пост и его ответ, если на них одновременно задано много вопросов и даны ответы.

Возвращаясь к вашим вопросам:

  • вопрос 1 : у вас была проблема с круглыми скобками, которые я исправил в вашем посте
  • вопрос 2: valueBox может отображаться только в dashboardPage, а не в fluidPage. Это вытекает из ответа Джо Ченга здесь :

    Извините, но valueBoxOutput и другие функции shinydashboard доступны только при использовании с dashboardPage.

  • вопрос 3: вы можете использовать observe и updateSelectInput, чтобы изменить варианты в selectInput в соответствии с выбранной вкладкой панели. Для этого сначала нужно создать id для tabsetPanel.

Вот рабочий код:

library(shiny)
library(plotly)
library(ggplot2)
library(shinydashboard)

df <- structure(
  list(
    Dead = c(0L, 0L, 0L, 0L, 0L, 1L, 9L, 0L, 0L, 0L),
    Case = c(120L, 70L, 50L, 40L, 39L, 20L, 18L, 13L, 9L, 2L),
    Recovered = c(30L, 0L, 18L, 13L, 19L,
                  10L, 0L, 16L, 0L, 1L),
    Critical = c(0L, 0L, 0L,
                 0L, 8L, 4L, 0L, 3L, 2L, 0L),
    Date = c(
      "18/03/2020",
      "17/03/2020",
      "16/03/2020",
      "15/03/2020",
      "14/03/2020",
      "13/03/2020",
      "12/03/2020",
      "11/03/2020",
      "10/03/2020",
      "09/03/2020"
    )
  ),
  class = "data.frame",
  row.names = c(NA,
                10L)
)

df$Date = as.Date(df$Date, format = "%d/%m/%Y")
ui <- fluidPage(
  title = 'testing',
  sidebarLayout(
    sidebarPanel(
      helpText(),
      selectInput("x", "Choose X-axis data", choices = names(df), selected = "Date"),
      uiOutput("second_select"),
      # Input: Slider for the number of observations to generate ----
      sliderInput("n",
                  "No. of bins:",
                  value = 5,
                  min = 1,
                  max = 15) ,
    ),
    mainPanel(
      tabsetPanel(
        id = "tabs",
        tabPanel("ggplot", plotlyOutput("regPlot1")),
        tabPanel("default plot", plotOutput("regPlot2")),
        tabPanel("Histogram", plotlyOutput("regPlot3"))
      )
    )
  )
)

server <- function(input, output, session) {

  Graphcase <- reactive({
    Gchoice<-input$x
  })
  myData <- reactive({
    df[, c(input$x, input$y)]
  })
  #plot
  output$regPlot1 <- renderPlotly({
    req(input$x)
    req(input$y)
    # comment the if and else(block) to make run the code
    if(Graphcase()=="Date"){

      ggplotly(ggplot(data = myData(),
                      aes_string(x = input$x, y = input$y)) +
                 geom_line( color="blue") +
                 geom_point(shape=21, color="black", fill="gray", size=4) +
                 theme(axis.text.x = element_text(color="#993333",
                                                  size=10, angle=45,hjust = 1),
                       axis.text.y = element_text(color="#993333",
                                                  size=10, angle=45,hjust = 1)) +
                 scale_x_date(date_labels = "%b/%d"))

    }else{
      ggplotly(ggplot(data = myData(),
                      aes_string(x = input$x, y = input$y)) +
                 geom_line( color="blue") +
                 geom_point(shape=21, color="black", fill="gray", size=4) +
                 theme(axis.text.x = element_text(color="#993333",
                                                  size=10, angle=45,hjust = 1),
                       axis.text.y = element_text(color="#993333",
                                                  size=10, angle=45,hjust = 1)))

    }
  })

  # plot2
  output$regPlot2 <- renderPlot({
    par(mar = c(4, 4, .1, .1)) # margin lines
    plot(myData(), data = df)
  })
  #plot 3

  observe({
    if(input$tabs == "Histogram"){
      updateSelectInput(session = session,
                        inputId = "x",
                        choices = names(subset(df, select = -c(Date))))

      output$second_select <- renderUI(NULL)
    }
    else {
      updateSelectInput(session = session,
                        inputId = "x",
                        choices = names(df),
                        selected = "Date")

      output$second_select <- renderUI({
        selectInput("y", "Choose Y-axis data", choices = names(df))
      })
    }
  })
  output$regPlot3 <- renderPlotly({
    ggplotly(ggplot(data = myData(), aes_string(x = input$x)) +
               geom_histogram(color="black",
                              fill="blue",
                              binwidth=input$n)
    )
  })

}

shinyApp(ui, server)

Редактировать: если Вы хотите удалить вторую selectInput, когда нажимаете на вкладку «Гистограмма», вам нужно использовать uiOutput и renderUI. Кроме того, чтобы предотвратить ошибку из-за отсутствия входных данных на первых двух графиках, используйте req(), чтобы сообщить Shiny, что вам нужны эти два входа, прежде чем начинать вычисление двух графиков. В результате я изменил приведенный выше код.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...