根据组更改stat_summary颜色,并将文本添加到ggplot2 boxplot中的标签

时间:2016-01-30 04:34:06

标签: r ggplot2 label

关注此问题:Add number of observations per group in ggplot2 boxplot,如何更改stat_summary的颜色?

以下是示例代码:

give.n <- function(x){
      return(c(y = median(x)*1.05, label = length(x))) 
    }    


p <- ggplot(mtcars, aes(factor(vs), mpg, colour = factor(am))) + 
      geom_boxplot() +
      stat_summary(fun.data = give.n, geom = "text", fun.y = median,
                   position = position_dodge(width = 0.75))
p

因此,当我执行以下操作来更改颜色时,它不起作用(它只给我一个组合数字)

stat_summary(fun.data = give.n, geom = "text", fun.y = median,
                   position = position_dodge(width = 0.75), colour =   c("black", "red"))

当我在下面添加文字&#34; n =&#34;它也不起作用。 (我尝试在函数本身中添加&#34; n =&#34;通过执行以下操作:

give.n <- function(x){
      return(c(y = median(x)*1.05, label = paste0("n=",length(x)))) 
    } 

但我收到以下错误:

 Error: Discrete value supplied to continuous scale

1 个答案:

答案 0 :(得分:1)

对于颜色,您希望使用scale_colour_manual添加这些颜色,因此绘图调用如下所示:

p <- 
    ggplot(mtcars, aes(factor(vs), mpg, colour = factor(am))) + 
    geom_boxplot() +
    stat_summary(fun.data = give.n, geom = "text", fun.y = median,
               position = position_dodge(width = 0.75)) +
    scale_colour_manual(values = c("black", "red"))

添加&#34; n =&#34;的答案与此问题重复:Use stat_summary to annotate plot with number of observations。您需要在data.frame(...)函数中使用give.n而不是c(...)

give.n <- 
    function(x){
      return(data.frame(y = median(x)*1.05, label = paste0("n=",length(x)))) 
    } 

编辑: 重新评论仅改变stat_summary项目的颜色,这被证明有点棘手,因为我认为你不能有多个scale_colour_manual层。但是,在这种情况下,您可以使用填充美学框图,并为文本geom留下颜色美感。 为了使它更清洁,我已经从ggplot(...)调用中获取了颜色并填充了美学,并将它们放在每个geom中:

p <- 
    ggplot(mtcars, aes(factor(vs), mpg)) + 
    geom_boxplot(aes(fill = factor(am))) +
    stat_summary(aes(colour = factor(am)), fun.data = give.n, 
                 geom = "text", fun.y = median, position = position_dodge(width = 0.75)) +
    scale_colour_manual(values = c("black", "red"))

然后,如果要为框图填充指定颜色,可以使用scale_fill_manual(...)