如何使用条件将数据添加到 ggplot 使其具有交互性?

How can I use conditions to add data to a ggplot making it interactive?

这是我在Whosebug上的第一个问题,所以如果我的问题描述不完整,请原谅我。 我正在使用 R shiny 制作交互式绘图。目的是比较不同城市的空气质量数据。这应该在 ggplot 中完成,用户可以在其中 select 污染物(y 轴)和可能的相关因子(例如气温,x 轴)。然后,用户应该能够 select 所有应该绘制数据的城市(作为 CheckboxGroupInput)。选择两个变量 (x-/y-axis) 效果很好,但我很难同时绘制多个城市。

我已经创建了输入,看起来效果不错。我也可以一次绘制一个城市。我还设法绘制了几个 selected 城市,但是它们没有绘制在同一个 ggplot 中,但只有最上面的图是可见的(参见下面的简化代码)。

UI:

library(shiny)
library(ggplot2)

berlin_d <- read.csv("berlin_d.csv")
london_d <- read.csv("London_d.csv")
warsaw_d <- read.csv("Warsaw_d.csv")


checkboxGroupInput(
          inputId = "city",
          label = "select a city/multiple cities",
          choices = c(
            "Berlin" = "Berlin",
            "London" = "London",
            "Warsaw" = "Warsaw"
          )
        ),

      selectInput(
        inputId = "box1",
        label = "select a variable to plot (x-axis)",
        choices = c("temperature" = "temp", 
          "month" = "month",
          "weekday" = "weekday"
        ),
        selected = "temp"
      ),


    selectInput(
      inputId = "box2",
      label = "select a pollutant to plot (y-axis)",
      choices = c("Ozone" = "O3",
                  "NO2" = "NO2",
                  "PM10" = "PM10"
      ),
    )

服务器:

output$plot <- renderPlot(ggplot()+
geom_point(if (input$city=="Berlin") {aes(berlin_d[[input$box1]], berlin_d[[input$box2]])})+
geom_point(if (input$city=="London") {aes(london_d[[input$box1]], london_d[[input$box2]])})+
geom_point(if (input$city=="Warsaw") {aes(warsaw_d[[input$box1]], warsaw_d[[input$box2]])})
)

我不明白为什么数据没有显示在同一个图中。有没有一种方法可以在一个 ggplot 中绘制数据并且仍然可以选择 select 个城市?

感谢任何帮助!

要回答您的问题,只需对您的代码进行少量更改就足以创建您正在寻找的功能。

你得看看input$city的输出。如果选中多个框,向量长度会发生变化,然后在选中 if-clause 时只会使用第一个元素。为避免这种情况,您可以重写 if-clause 如下

if ("Berlin" %in% input$city)

整个情节是这样的。

ggplot() +
    geom_point(if ("Berlin" %in% input$city) {aes(berlin_d[[input$box1]], berlin_d[[input$box2]])}) +
    geom_point(if ("London" %in% input$city) {aes(london_d[[input$box1]], london_d[[input$box2]])}) +
    geom_point(if ("Warsaw" %in% input$city) {aes(warsaw_d[[input$box1]], warsaw_d[[input$box2]])})

但是,更好的方法是创建一个包含所有数据的数据集,其中 city 只是一个分组变量。然后创建一个响应式表达式,根据输入过滤器 (input$city) 对 shiny 中的数据进行子集化。然后,您可以通过一次调用 ggplot 并将城市设置为颜色的因子变量来创建一个图。