每次尝试选择其他单选按钮时,我都试图更新ggplot图表,但是它不能正常工作。我想发生的是选择单选按钮更改图形上的颜色。有三个单独的类别,因此理想情况下,如果选择了第一个按钮:类别1将为绿色(或我选择的任何颜色),类别2和3将为相同的颜色,但不同于1。这是我的代码:< / p>
# 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)
每次选择单选按钮时,条形图都会移动,并且似乎将未选择的两个类别归为一组。如何使条形图保持静态,但颜色对单选按钮的选择做出适当反应?
是否有更好的方法可以做到这一点?任何帮助将不胜感激!
答案 0 :(得分:2)
我忽略了您的列C1
,C2
和C3
,并使用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
的颜色分配更加可靠;这只是最简单的方法。