【问题标题】:R Shiny ggplot color aesthetic reactive to inputR Shiny ggplot 颜色美学对输入有反应
【发布时间】:2020-05-07 22:40:38
【问题描述】:

我正在尝试创建一个闪亮的应用程序,其中 ggplot 是主要的绘图输出,并且我已经达到了用户可以使用 dateRangeInput 按日期过滤,以及使用 selectVarInput 选择 X 和 Y 轴的地步。但是,在主要的 ggplot 输出中,我希望该图具有颜色美感,可以根据日期分离不同的响应。这是我到目前为止所拥有的,但返回一条错误消息说“美学必须是长度 1 或与数据 (10) 相同:颜色”。任何帮助将不胜感激!

library(tidyverse)
library(shiny)

sampledf <- tibble(Name = c("John Smith"), 
`Test 1` = c("Test 1"), 
`Date` = lubridate::as_date(c("2020-04-22","2020-04-22", "2020-04-22", "2020-04-24", "2020-04-24", "2020-04-24", "2020-04-24", "2020-04-26", "2020-04-26", "2020-04-26")), 
`Result 1` = rnorm(1:10), 
`Result 2` = rnorm(1:10), 
`Result 3` = rnorm(1:10))

# Define UI for application
ui <- navbarPage(
    "Title",

    tabPanel(
        "Tab 1",
        sidebarPanel(
            h4("Inputs"),
            selectInput(
                "Name_Select",
                label = "Select Name",
                choices = sampledf$Name,
                selected = TRUE
            ),
            dateRangeInput(
                "dates",
                label = "Dates",
                start = min(sampledf$Date),
                end = max(sampledf$Date)
            ),
            varSelectInput("X_Axis",
                           label = "Select Variable 1",
                           data = sampledf,
              ),
            varSelectInput("Y_Axis",
                           label = "Select Variable 2",
                           data = sampledf,
               ),
        )
    ),

    mainPanel(plotOutput("plot")),

    tabPanel("Tab2")

)

# Define server logic
server <- function(input, output) {

    output$plot <- renderPlot({

        Data %>% 
            filter(sampledf$Date >= input$dates[1], sampledf$Date <= input$dates[2]) %>%
            ggplot(mapping = (aes_string(x = input$X_Axis, y = input$Y_Axis))) +
            geom_line(color = input$dates) +
            geom_point(color = input$dates)
})
}

# Run the application 
shinyApp(ui = ui, server = server)

【问题讨论】:

    标签: r ggplot2 shiny


    【解决方案1】:

    首先,一个小问题:您不需要在aes_string(...) 周围加上括号,所以它应该是mapping = aes_string(...),但这可能不会导致问题,因为错误消息引用了颜色。

    问题在于 input$datesdateRangeInput(),这意味着它返回 2 个日期的向量(正如您在图上方的 filter() 命令中正确引用的那样。您可以使用日期,但您需要在 sampledf 数据框中引用“日期”。因此,在这种情况下,将最后两行更改为此,它应该可以工作:

    geom_line(color = Date) +
    geom_point(color = Date)
    

    话虽如此,您应该意识到特定日期的配色方案将取决于使用此代码选择的范围。这意味着,如果您的范围内有 10 天,“第 4 天”的颜色将不会始终与此代码相同,而是取决于所选日期的范围。如果您对此感到满意,请继续,但您可能需要包含一个 scale_color_manual 函数来根据日期明确设置颜色。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-11
      • 1970-01-01
      • 1970-01-01
      • 2019-06-30
      • 1970-01-01
      • 2017-11-17
      • 2020-10-28
      • 1970-01-01
      相关资源
      最近更新 更多