首页 > 解决方案 > 闪亮的散点图

问题描述

我正在尝试根据已加载的 csv 创建散点图,但是当我运行代码时,当我包含 aes 映射时,要么没有显示绘图,要么出现错误:“应该使用aes()or创建映射aes_()。”

谁能给我指点我哪里出错了?

代码:

library(shiny)
library(ggplot2)

ui <- (fluidPage(
titlePanel("Pig Breeds"),
sidebarLayout(
sidebarPanel(
  selectInput(inputId = "x", 
              label = "Pig Breeds:", 
              choices = c("total_pigs", "female_breeding_herd", 
                          "in_pig_sows", "in_pig_gifts", "other_sows", 
                          "maiden_gilts", "boars_for_service", "other_pigs"),
              selected = "total_pigs"),
  selectInput(inputId = "y",
              label = "Year by year change:",
              choices = c(2016, 2017, 2018, "year_on_year_change"),
              selected = 2016),
  actionButton(inputId = "update", label = "update")
            ),
mainPanel = (
  plotOutput(outputId = "scatterplot")
  )
)
)
)

server <- (function(input, output) {
output$scatterplot <- renderPlot({
ggplot(data=(read.csv("eu_pigs.csv")),
            aes(x = output$x, y = output$y) + 
            geom_point())
observeEvent(input$update, {print(as.numeric(input$update))})
       }
    )
  }
 )

shinyApp(ui, server)

标签: rggplot2shinyrstudioscatter-plot

解决方案


正如错误消息所说,您使用aes不正确。该函数采用列名,而不是变量引用。也就是说,更换

aes(x = output$x, y = output$y)

经过

aes(x = x, y = y)

或者,您更有可能希望能够从输入中控制绘图,因此您希望使用

aes_string(x = input$x, y = input$y)

您的代码中还有很多杂散的括号和大括号。删除那些。此外,mainPanel是您需要调用的函数。相反,您的代码正在为其分配一些东西。

最后,你实际上需要绘制你的情节。在所有这些事情都修复之后,相关代码如下所示:

ui <- fluidPage(
    titlePanel("Pig Breeds"),
    sidebarLayout(
        sidebarPanel(…),
        mainPanel(
            plotOutput(outputId = "scatterplot")
        )
    )
)

server <- function(input, output) {
    output$scatterplot <- renderPlot({
        p = ggplot(data = read.csv("eu_pigs.csv")) +
            aes_string(x = input$x, y = input$y) +
            geom_point()
        plot(p)
        observeEvent(input$update, print(as.numeric(input$update)))
    })
}

如果绘图对象是您在函数中执行的最后一件事renderPlot,您可以省略plot

output$scatterplot <- renderPlot({
    ggplot(data = read.csv("eu_pigs.csv")) +
        aes_string(x = input$x, y = input$y) +
        geom_point()
})

推荐阅读