R ggplot颜色对输入有反应的美感

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

我正在尝试创建一个闪亮的应用程序,其中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个回答
0
投票

首先,要注意的一点是:您不需要在aes_string(...)周围加上括号,因此它应该为mapping = aes_string(...),但这很可能不会引起问题,因为错误消息引用了颜色。

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

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

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

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