简体   繁体   English

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

[英]Color based on difference between bars using ggplot

I've done quite a bit of searching and am trying to do the following. 我做了很多搜索,并尝试做以下事情。 I have a bar plot with two dodged bars for each value. 我有一个条形图,每个值都有两个躲闪的条形图。 Each bar represents a percentage. 每个条形代表一个百分比。 (roughly how it looks as I cannot post images yet) (大致看起来如何,因为我无法发布图像)

Feature |XXXXXXXXXXXXXX  %50
        |XXXXXXXX        %25

What I'd like to do is change the color of either of the bars to "RED" whenever the difference in percentage is > 15 我想做的是,当百分比差异大于15时,将任一条的颜色更改为“RED”

Here's the data I'm using: 这是我正在使用的数据:

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

Code: 码:

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

So basically if we looked at the "mock" at the top. 所以基本上如果我们看看顶部的“模拟”。 Because the percentages between the 2 bars is greater than 15% I'd like one of the bars to be a different color(a third color) like below: 因为2条之间的百分比大于15%,我希望其中一条是不同的颜色(第三种颜色),如下所示:

在此输入图像描述

I've thought about using a ifelse to set the color I just haven't been able to implement it. 我想过使用ifelse来设置我实际上无法实现的颜色。 My thinking is using the ifelse to return the color I want to use. 我的想法是使用ifelse返回我想要使用的颜色。 So "if" the difference between the 2 bars is > 15 return this color "else" return another color. 因此,“如果”2条之间的差异> 15则返回此颜色“否则”返回另一种颜色。 Does anyone know if this is possible? 有谁知道这是否可能?

You can create the vector of filling colors prior to your ggplot call. 您可以在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()

在此输入图像描述 You could probably do this using the hidden variables in the ggplot call as well, but it would be trickier. 您可以使用ggplot调用中的隐藏变量来执行此操作,但这会更棘手。

My answer is in the same lines as @nongkrong: 我的回答和@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

Using dplyr/tidyr: 使用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")

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM