低于平均值的列的条件色调

时间:2015-12-19 08:43:55

标签: r ggplot2

我想更改特定列的色调(如果低于平均值):

library(reshape2)
library(ggplot2)

dat <- read.table(text=" cars    trucks  suvs
1   2   4
3   5   4
6   4   6
4   5   6
9   12  16", header=TRUE, as.is=TRUE)
dat$day <- factor(c("Mo", "Tu", "We", "Th", "Fr"), 
             levels=c("Mo", "Tu", "We", "Th", "Fr"))

mdat <- melt(dat, id.vars="day")
head(mdat)
ggplot(mdat, aes(variable, value, fill=day)) + 
  geom_bar(stat="identity", position="dodge")+
geom_line(stat = "hline", yintercept = "mean", aes(colour = day, group=day), size=1.5, linetype="dashed")

例如:列车/星期五应该稍微浅一些,因为它低于它的平均值:

Plot

是否可以在ggplot中执行此操作?

1 个答案:

答案 0 :(得分:4)

您可以创建一个标识符变量,指示该值是否低于平均值。

mdat$below.mean <- ave(mdat$value, mdat$day, FUN = function(x) x > mean(x))

这会在数据集中添加一个逻辑整数列,其中高于均值的所有值都被编码为1,其他值被编码为0

> mdat
   day variable value below.mean
1   Mo     cars     1          0
2   Tu     cars     3          0
3   We     cars     6          1
4   Th     cars     4          0
5   Fr     cars     9          0
6   Mo   trucks     2          0
7   Tu   trucks     5          1
8   We   trucks     4          0
9   Th   trucks     5          0
10  Fr   trucks    12          0
11  Mo     suvs     4          1
12  Tu     suvs     4          0
13  We     suvs     6          1
14  Th     suvs     6          1
15  Fr     suvs    16          1

现在,您可以使用该变量通过alpha参数创建低于平均值的条形码:

ggplot(mdat, aes(variable, value, fill=day, alpha=factor(below.mean))) + 
  geom_bar(stat="identity", position="dodge") +
  scale_alpha_discrete(range = c(0.5,1)) +
  guides(alpha=FALSE) +                        # this remove the 'alpha' legend
  theme_minimal()

给出:

enter image description here