繁体   English   中英

在R Shiny图上选择不同的彩色线

[英]Select different coloured lines on R Shiny plot

我正在尝试创建一个闪亮的应用程序,该应用程序最多显示2条不同的彩色线,具体取决于用户选择查看的颜色。 但是,我一直收到“意外字符”错误。

我认为问题出在selectInput(inputId = "z", label = "Source", choices = c("social_media", "google_ads"), selected = c("social_media", "google_ads"), multiple = TRUE)在下面的代码中为selectInput(inputId = "z", label = "Source", choices = c("social_media", "google_ads"), selected = c("social_media", "google_ads"), multiple = TRUE) ,因为当我替换choices并用source selected时,图形似乎可以正常工作(尽管不允许用户选择和查看其他选项)。

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或两者(默认情况下两者)的结果。

非常感谢,希望这有意义。

您可以通过实现

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因为您不想将source评估为变量。

请记住,要安装并加载库(tidyverse),ggplot2也是tidyverse的一部分,因此您可以将library(ggplot2)替换为library(tidyverse) 如果您真的不想使用tidyverse,则只需使用df[df$source %in% input$z, ]过滤数据

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM