使用stat_summary和text geoms在ggplot中为每个组添加单个标签

时间:2020-10-02 04:29:46

标签: r ggplot2

我想将计数添加到使用stat_summary()的ggplot中。

我在要求文本向量与数据长度相同的问题上遇到了问题。

在下面的示例中,您可以看到正在绘制的内容多次是同一标签。

在y轴上设置位置的解决方法是将多个标签堆叠在一起。视觉效果有点奇怪(尤其是当您有成千上万的观察结果时),并且不够专业。您将不得不信任我-所附图片无法完全传达出它的怪异性。

我想知道别人是否另辟worked径。这是针对具有动态输入的光泽图,因此文本不能以硬编码方式覆盖。

我很确定ggplot不是针对我想要的stat_summary行为设计的,我可能不得不放弃stat_summary并创建一个新的摘要数据框,但是我想我会首先检查其他人是否有提供一些巫术。

这是未设置y位置的图:

library(dplyr)
library(ggplot2)


df_x <- data.frame("Group" = c(rep("A",1000), rep("B",2) ),
                   "Value" = rnorm(1002))
df_x <-  df_x %>%  
  group_by(Group) %>%
  mutate(w_count = n())
      

ggplot(df_x, aes(x = Group, y = Value)) +

    stat_summary(fun.data="mean_cl_boot", size = 1.2) +
    geom_text(aes(label = w_count)) +
    coord_flip() +
    theme_classic()


enter image description here

这是我的骇客


ggplot(df_x, aes(x = Group, y = Value)) +

    stat_summary(fun.data="mean_cl_boot", size = 1.2) +
    geom_text(aes(y = 1, label = w_count)) +
    coord_flip() +
    theme_classic()

enter image description here

2 个答案:

答案 0 :(得分:2)

创建一个df_text,其中包含标签的分组信息。然后使用annotate

library(dplyr)
library(ggplot2)

set.seed(123)

df_x <- data.frame("Group" = c(rep("A",1000), rep("B",2) ),
                   "Value" = rnorm(1002))

df_text <- df_x %>% 
  group_by(Group) %>% 
  summarise(avg = mean(Value),
            n = n()) %>%
  ungroup()

yoff <- 0.0
xoff <- -0.1

ggplot(df_x, aes(x = Group, y = Value)) +
  stat_summary(fun.data="mean_cl_boot", size = 1.2) +
  annotate("text", 
           x = 1:2 + xoff, 
           y = df_text$avg + yoff,
           label = df_text$n) +
  coord_flip() +
  theme_classic()

enter image description here

答案 1 :(得分:1)

我发现了另一种方法,该方法对于情节在其排序和过滤中是动态的并且对于刻面效果很好时,则更为健壮。更加健壮,因为它使用stat_summary作为文本。

library(dplyr)
library(ggplot2)


df_x <- data.frame("Group" = c(rep("A",1000), rep("B",2) ),
                   "Value" = rnorm(1002))

counts_df <- function(y) {
  return( data.frame( y = 1, label = paste0('n=', length(y)) ) )
}


ggplot(df_x, aes(x = Group, y = Value)) +

    stat_summary(fun.data="mean_cl_boot", size = 1.2) +
    coord_flip() +
    theme_classic()

p + stat_summary(geom="text", fun.data=counts_df)