选择R上闪亮的情节不同颜色的线

问题描述 投票:0回答:1

我试图创建一个闪亮的应用程序,显示这取决于用户选择看高至2条不同颜色的线。不过,我不断收到一个“意外的字符”错误。

我认为这个问题是在下面的代码行selectInput(inputId = "z", label = "Source", choices = c("social_media", "google_ads"), selected = c("social_media", "google_ads"), multiple = TRUE),因为当我替补choicesselectedsource,图表似乎工作(虽然不允许用户选择并观看不同的选项)。

df是一个数据帧,看起来像这样:

av_purchase_count     days_since_first_use    source
2                     1                       social_media
5                     2                       social_media
4                     1                       google_ads
6                     2                       google_ads

...这里是我试过的代码:

library(shiny)
library(ggplot2)
df <- read_xlsx("~/df.xlsx")

ui <- fluidPage(

   titlePanel("df"),

   sidebarLayout(
      sidebarPanel(
         selectInput(inputId = "x", label = "Days since first use", choices = "days_since_first_use", selected = "days_since_first_use"),
         selectInput(inputId = "y", label = "Average Purchase Count", choices = "av_purchase_count", selected = "av_purchase_count"),
         selectInput(inputId = "z", label = "Source", choices = c("social_media", "google_ads"), selected = c("social_media", "google_ads"), multiple = TRUE)
      ),

      mainPanel(
         plotOutput("scatterplot")
      )
   )
)

server <- function(input, output) {

   output$scatterplot <- renderPlot({
      # generate bins based on input$bins from ui.R
     ggplot(data = df, aes_string(x = input$x, y = input$y, colour = input$z)) +
       geom_point()
      })
}

shinyApp(ui = ui, server = server)

我想结束图表,让用户选择他们是否希望看到google_adssocial_media,或两者的结果(默认情况下,两者)。

非常感谢,希望这是有道理的。

r shiny
1个回答
1
投票

您可以通过它实现

output$scatterplot <- renderPlot({
  ggplot(
    data = df %>% filter(source %in% input$z),
    aes_string(x = input$x, y = input$y)
  ) + geom_point(aes(colour = source))
})

可变input$z反映了用户已经选择显示(google_ads或social_media或两者)。这将触发剧情重绘每次本身的变化反应载体。每次它改变时,过滤数据帧中的用户想通过df %>% filter(source %in% input$z)仅查看自己保存。要注意的另一件事是基于“源”以色点,你需要使用aes(color = source)aes_string因为你不想来评价源为一个变量。

请记住,安装并加载库(tidyverse),GGPLOT2也tidyverse的一部分,所以你可以用library(ggplot2)取代library(tidyverse)。如果你真的不想使用tidyverse,那么就使用df[df$source %in% input$z, ]过滤数据

© www.soinside.com 2019 - 2024. All rights reserved.