如何在存在多个组的单个直方图中绘制多条平均线?
How to plot multiple mean lines in a single histogram with multiple groups present?
我正在单个直方图上绘制两个变量的分布。我有兴趣通过虚线或类似的东西在该图上突出显示每个分布的平均值(但希望与代码的 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 数吗?
我已经制作了一些可重现的代码,可能会帮助您解决问题。
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
我正在单个直方图上绘制两个变量的分布。我有兴趣通过虚线或类似的东西在该图上突出显示每个分布的平均值(但希望与代码的 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 数吗?
我已经制作了一些可重现的代码,可能会帮助您解决问题。
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