首页 > 解决方案 > 在闪亮的条形图中更改条形的颜色

问题描述

我有一个闪亮的应用程序,它基本上根据用户在表格中选择的线条生成一个图表。有两个表:第一个生成左侧的前 3 个柱(基准),其他来自第二个表。图表图像

我对您的问题是:您认为,是否可以将左侧的前 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)
    })

谢谢,

雷米

标签: rggplot2shiny

解决方案


要影响前 3 个条的颜色,您需要使用另一个美学值,而fill不是variable

例如:

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))

给出:

在此处输入图像描述


推荐阅读