【问题标题】:How to plot multiple mean lines in a single histogram with multiple groups present?如何在存在多个组的单个直方图中绘制多条平均线?
【发布时间】:2020-11-10 22:55:05
【问题描述】:

我在一个直方图上绘制两个变量的分布。我有兴趣通过虚线或类似的东西突出显示该图上每个分布的平均值(但希望与代码的 aes 部分中已经存在的颜色相匹配)。
我该怎么做?

这是我目前的代码。

hist_plot <- ggplot(data, aes(x= value, fill= type,  color = type)) +
geom_histogram(position="identity", alpha=0.2) +
labs( x = "Value", y = "Count", fill = "Type", title = "Title") +
guides(color = FALSE)

另外,有没有办法在这张图上显示每种类型的 n 计数?

【问题讨论】:

    标签: r ggplot2 histogram mean


    【解决方案1】:

    我已经编写了一些可重现的代码,可以帮助您解决问题。

    library(tidyverse)
    
    # Generate some random data
    df <-  data.frame(value = c(runif(50, 0.5, 1), runif(50, 1, 1.5)), 
                      type = c(rep("type1", 50), rep("type2", 50)))
    
    # Calculate means from df
    stats <- df %>% group_by(type) %>% summarise(mean = mean(value),
                                                 n = n())
    
    # Make the ggplot
    ggplot(df, aes(x= value, fill= type,  color = type)) +
      geom_histogram(position="identity", alpha=0.2) +
      labs(x = "Value", y = "Count", fill = "Type", title = "Title") +
      guides(color = FALSE) +
      geom_vline(data = stats, aes(xintercept = mean, color = type), size = 2) +
      geom_text(data = stats, aes(x = mean, y = max(df$value), label = n), 
                size = 10, 
                color = "black")
    

    如果事情按预期进行,您将得到类似于以下情节的结果。

    histogram with means

    【讨论】:

    • 如果手段彼此接近,你将如何阻止 geom_text 重叠?
    • 我的意思是物理上接近,而不是说数字。
    • 查看 ggrepel 包。它应该只是将 geom_text() 替换为 geom_text_repel() cran.r-project.org/web/packages/ggrepel/vignettes/ggrepel.html
    • 我就是这样做的,它解决了这个问题。谢谢!
    猜你喜欢
    • 2013-08-01
    • 2013-04-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多