使用ggplot基于条之间差异的颜色

时间:2015-08-10 14:29:49

标签: r

我已经做了很多搜索,并尝试执行以下操作。我有一个条形图,每个值都有两个躲闪的条形图。每个条形代表一个百分比。 (大致看起来如何,因为我无法发布图像)

Feature |XXXXXXXXXXXXXX  %50
        |XXXXXXXX        %25

我想做的是,只要百分比差异> 1,就可以将任一条的颜色更改为“RED”。 15

以下是我正在使用的数据:

Feature variable          value
A       "Percent Done"    50
B       "Planned"         25
A       "Percent Done"    10
B       "Planned"         80

代码:

p3 <- ggplot(plotdata, aes(x = Feature, y = value, fill = variable))
p3 <- p3 + geom_bar( position ="dodge", stat ="identity")+ 
      coord_flip() + theme_minimal()

所以基本上如果我们看看顶部的“模拟”。因为2条之间的百分比大于15%,我希望其中一条是不同的颜色(第三种颜色),如下所示:

axios

我已经考虑使用ifelse来设置我无法实现的颜色。我的想法是使用ifelse返回我想要使用的颜色。所以“如果”2条之间的差异是> 15返回此颜色“else”返回另一种颜色。有谁知道这是否可行?

3 个答案:

答案 0 :(得分:2)

您可以在ggplot来电之前创建填充颜色的向量。

## Sample data
dat <- data.frame(`Percent Done`=c(25,10,15),
                  Planned=c(50,80,20),
                  Feature=factor(c("A","B","C"), levels=c("C","B","A")))
library(reshape2)
dat <- melt(dat, id.vars = "Feature")  # reshape the data to long format

## Get the fill colors
dat <- dat[order(dat$Feature, dat$variable, decreasing = T), ]
dat$fills <- ifelse(c(0, abs(diff(dat$value))) > 15, "red", "yellow")
dat$fills[c(T,F)] <- "black"

ggplot(dat, aes(Feature, value, group=variable, order=rev(variable))) +
  geom_histogram(stat="identity", aes(fill=fills), position=position_dodge()) +
  scale_fill_manual(values=c("black","red","yellow"), labels=c("Plan",">15%", "Within 15%")) +
  coord_flip() +
  theme_bw()

enter image description here 您可以使用ggplot调用中的隐藏变量来执行此操作,但这会更棘手。

答案 1 :(得分:1)

我的回答与@nongkrong:

相同
set.seed(1)
x<-data.frame(feat=letters[1:20],plan=runif(20),exec=runif(20)) # create some dummy data
x$col<-((x$plan-x$exec)>=.15)+1 #create a color column
library(reshape2)
y<-melt(x,id.vars = c("feat","col")) # make it long
y$col[which(y$variable=="plan")]<-0 # create a color difference between planed and executed
y$col<-as.factor(y$col) # make it factor, so we can use it in ggplot
ggplot(y,aes(feat,value,fill=col))+geom_bar(position=position_dodge(),stat="identity")+scale_fill_manual(values=c("black","green","red")) # Create a scale fill with the desired colors

答案 2 :(得分:1)

使用dplyr / tidyr:

data.frame('Feature' = c('A', 'A', 'B', 'B'), 
           'variable' = c("PercentDone", "Planned", "PercentDone", "Planned"),
           "value"=c(35,50,10,80)) %>% 
   spread(variable, value) %>% 
   mutate(colour=ifelse(Planned-PercentDone <= 15, "Within 15%", ">15%")) %>% 
   gather("variable", "value", 2:3) %>% 
   mutate(colour = ifelse(variable == "Planned", "Plan", colour)) %>%
   ggplot(aes(x=Feature, y=value, fill=relevel(factor(colour), ref="Plan"))) +
   geom_bar(stat="identity", position="dodge")

enter image description here