简体   繁体   English

如何在存在多个组的单个直方图中 plot 多条平均线?

[英]How to plot multiple mean lines in a single histogram with multiple groups present?

I am plotting a distribution of two variables on a single histogram.我在单个直方图上绘制两个变量的分布。 I am interested in highlighting each distribution's mean value on that graph through a doted line or something similar (but hopefully something that matches the color present already in the aes section of the code).我有兴趣通过虚线或类似的东西突出显示该图上每个分布的平均值(但希望与代码的 aes 部分中已经存在的颜色相匹配)。
How would I do that?我该怎么做?

This is my code so far.到目前为止,这是我的代码。

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)

Also, is there any way to show the count of n for each type on this graph?另外,有没有办法在这张图上显示每种类型的 n 计数?

i've made some reproducible code that might help you with your problem.我制作了一些可重现的代码,可以帮助您解决问题。

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")

If things go as intended, you'll end up something akin to the following plot.如果 go 符合预期,您最终会得到类似于以下 plot 的东西。

histogram with means带均值的直方图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM