根据单选按钮选择更改 ggplot 的颜色(R Shiny)

Change Colors of ggplot based on Radio Button Selection (R Shiny)

每次您 select 一个不同的单选按钮时,我都试图更新一个 ggplot 图表,但它工作不正常。我想要发生的是单选按钮的 selection 改变图表上的颜色。有三个独立的类别,所以理想情况下,如果第一个按钮是 selected:类别 1 将是绿色(或我选择的任何颜色),类别 2 和 3 将是相同的颜色,但与 1 不同。这里是我的代码:

# Define UI for application
ui = fluidPage(
  navbarPage("Example Problem",
            
             tabPanel("Example",
                      tabname="example",
                      icon=icon("thumbs-up"),
                      prettyRadioButtons(inputId = "rb", 
                                         label = "Make a selection:",
                                         c("3","4","5"),
                                         animation = "pulse",
                                         inline=TRUE),               
                      plotOutput("plot_example")
             )
                      ))


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

  
  output$plot_example=renderPlot({
    df=as.data.frame(table(mtcars$carb,mtcars$gear))
    df$C3=ifelse(df$Var2==3,1,0)
    df$C4=ifelse(df$Var2==4,1,0)
    df$C5=ifelse(df$Var2==5,1,0)

    
    switch(input$rb,
           
           "3"=ggplot(data=df, aes(x=Var1, y=Freq, fill=factor(C3))) + geom_bar(stat="identity", position=position_dodge())+
             scale_fill_brewer(palette="Paired")+geom_text(aes(label=Freq), position=position_dodge(width=0.9), vjust=-0.25),
           "4"=ggplot(data=df, aes(x=Var1, y=Freq, fill=factor(C4))) + geom_bar(stat="identity", position=position_dodge())+
             scale_fill_brewer(palette="Paired")+geom_text(aes(label=Freq), position=position_dodge(width=0.9), vjust=-0.25),
           "5"=ggplot(data=df, aes(x=Var1, y=Freq, fill=factor(C5))) + geom_bar(stat="identity", position=position_dodge())+
             scale_fill_brewer(palette="Paired")+geom_text(aes(label=Freq), position=position_dodge(width=0.9), vjust=-0.25))
  })
  
  
}

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

条形图随着单选按钮的每个 select 离子移动,似乎将未 selected 的两个类别分组。如何保持条形图静态但颜色对单选按钮做出适当反应 selection?

有没有更好的方法可以做到这一点?如有任何帮助,我们将不胜感激!

我忽略了您的列 C1C2C3,并使用 Var2 作为 fill 变量。假设,这就是你想要的吗?

server <- function(input, output) {
  
  output$plot_example = renderPlot({
    df = as.data.frame(table(mtcars$carb, mtcars$gear))
    
    colors <- switch(
      input$rb,
      "3" = c("green", "grey", "grey"),
      "4" = c("grey", "green", "grey"),
      "5" = c("grey", "grey", "green")
    )

    ggplot(data = df, aes(x = Var1, y = Freq, fill = factor(Var2))) +
      geom_bar(stat = "identity", position = position_dodge(), colour = "black") +
      scale_fill_manual(values = colors) +
      geom_text(aes(label = Freq),
                position = position_dodge(width = 0.9),
                vjust = -0.25)
  })
}

如果您有更多变化,您可以使 scale_fill_manual 的颜色分配更可靠;这只是最简单的方法。