首页 > 解决方案 > Reactive Shiny Plot 不显示任何绘图。

问题描述

我有一个数据集,其中包含大约 30 年来所有 50 个州的房屋价值。列包括状态、年份、值等。我正在尝试创建一个交互式 Shiny 应用程序,用户可以在其中选择某些状态,以便它们将是图中唯一显示的状态。我已经成功地独立创建了所有状态的图,其中年份在 x 轴上,值在 y 轴上,按状态着色,并且还成功地对数据集进行了子集化,以便仅绘制一个状态图。

我是 Shiny 的新手,并且遇到了除 Input checkBox 功能以外的任何问题。我有什么明显的遗漏吗?

    ui <- fluidPage(
       checkboxGroupInput(inputId = "state", label = "States", choices = levels(AllData2$STATE),
        plotOutput(outputId = "hist")))

    server <- function(input, output) {
         output$hist <- renderPlot({
      plot(data = subset(AllData2, AllData2 == input$state), mapping = aes(x = Date, y = HomeValue, 
     color = STATE) + geom_line(size=2, alpha=0.8) + 
     scale_y_continuous(breaks = seq(0, 1000000, 50000)) + 
     scale_x_continuous(breaks = seq(1975, 2020, 5)) +
     ylab("Value in Dollars") + xlab("Year"))

     })
   }

    shinyApp(ui = ui, server = server)

除了复选框选项外,我的 Shiny App 中没有任何输出。感谢您的任何帮助。

标签: rshiny

解决方案


您的代码中只有语法错误。许多人:

  1. 您已包含plotOutput()在复选框组中,请将其放在它之外。
  2. 使用ggplot()代替plot()
  3. 你已经包含了里面的所有东西plot()如果你使用ggplot()的语法是:ggplot(data=AllData,mapping=aes())+geom_line()+scale_y_continuous()+scale_x_continuous()+labs(x="This is X label",y="This is ylab",color="This is the color legend label")

解决这些问题后,您的代码将起作用 如果您想要即时结果,只需复制粘贴即可:

library(shiny)
library(ggplot2)
library(dplyr)
ui <- fluidPage(
  column(12,checkboxGroupInput(inputId = "state", label = "States", choices = c(1,2,3,4,5))),
                     column(12,plotOutput(outputId = "hist")))

server <- function(input, output) {
  output$hist <- renderPlot({
    ggplot(data = subset(AllData2, AllData2$STATE %in% input$state), mapping = aes(x = Date, y = HomeValue, 
              color = STATE)) + geom_line(size=2, alpha=0.8) + 
           scale_y_continuous(breaks = seq(0, 1000000, 50000)) + 
           scale_x_continuous(breaks = seq(1975, 2020, 5)) +labs(x="Value in Dollars",y="Year")

  })
}

shinyApp(ui = ui, server = server)

推荐阅读