在Shiny的条形图中更改条形的颜色

时间:2019-03-19 14:01:10

标签: r ggplot2 shiny

我有一个Shiny应用程序,该应用程序基本上根据用户在表中选择的线生成图形。有两个表格:第一个表格产生左侧的前3个小节(基准),其他表格来自第二个表格。Image of graphs

我对您的问题是:您认为是否可以将左边的前3个小节保留为蓝色,并为其他所有颜色使用其他颜色?

这是我在应用程序中用于生成图形的代码:

output$graphPost <- renderPlot({
      s <- input$posttestsdata_rows_selected
      y <- input$benchmarkdata_rows_selected
      tempBench <- benchmarkData[y]
      meltedBench <- melt(tempBench)
      tempPost <- postTestsData[s]
      colnames(tempBench)[1] <- "x"
      colnames(tempPost)[1] <- "x"
      postTestsDataForGraph <- rbind(tempBench, tempPost)
      meltPostTests <- melt(postTestsDataForGraph)
      meltPostTests$x <- factor(meltPostTests$x, levels=unique(meltPostTests$x))
      postTestsPlot <<- ggplot() +
        geom_bar(data = meltPostTests, aes(x = as.factor(x), y = value, fill = variable), stat='identity', position = "dodge") + 
        theme(axis.line=element_blank(),
              axis.text.y=element_blank(),
              axis.ticks=element_blank(),
              axis.title.x=element_blank(),
              axis.title.y=element_blank(),
              panel.background=element_blank(),
              panel.border=element_blank(),
              panel.grid.major=element_blank(),
              panel.grid.minor=element_blank(),
              plot.background=element_blank()) + 
        geom_hline(yintercept = meltedBench$value, color = c("#1F497D", "#4F81BD", "#8DB4E3")) + 
        geom_text(aes(x = as.factor(meltPostTests$x), y = meltPostTests$value, fill=meltPostTests$variable, label = paste(meltPostTests$value,"%", sep = "")), position=position_dodge(width=0.9), vjust=-0.25) + 
        scale_fill_manual(values = c("#1F497D", "#4F81BD", "#8DB4E3"))
      return(postTestsPlot)
    })

谢谢

Rémi

1 个答案:

答案 0 :(得分:0)

To influence the colors of the first 3 bars, you need to use another value for aesthetic fill than variable

For example:

require(ggplot2)

set.seed(314)
dat <- data.frame(x = rep(1:3,10),
                  variable = sample(1:3, 30, replace = T))

dat$c <- as.factor(ifelse(dat$x == 1,1,dat$variable+1))



ggplot(dat, aes(x = interaction(variable,x), fill = c)) +
  geom_bar(data = dat, aes(fill = c), position = position_dodge()) +
  scale_x_discrete(breaks = c('2.1','2.2','2.3'),
                   labels = unique(dat$variable))

gives:

enter image description here