[英]Color based on difference between bars using ggplot
我做了很多搜索,并尝试做以下事情。 我有一个条形图,每个值都有两个躲闪的条形图。 每个条形代表一个百分比。 (大致看起来如何,因为我无法发布图像)
Feature |XXXXXXXXXXXXXX %50
|XXXXXXXX %25
我想做的是,当百分比差异大于15时,将任一条的颜色更改为“RED”
这是我正在使用的数据:
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%,我希望其中一条是不同的颜色(第三种颜色),如下所示:
我想过使用ifelse来设置我实际上无法实现的颜色。 我的想法是使用ifelse返回我想要使用的颜色。 因此,“如果”2条之间的差异> 15则返回此颜色“否则”返回另一种颜色。 有谁知道这是否可能?
您可以在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()
我的回答和@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
使用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.