我有一个由两个不同测量值组成的数据集,在不同样本(a 和 b)中测量的值(我们称之为高度和宽度)有非常不同的大小。我想使用平滑直方图来说明这两个测量值的可变性,无论其绝对大小如何,因此我一直使用
geom_density
。然而,使用 geom_density
计算的密度值同样彼此存在数量级的差异。
数据集:
library(tidyverse)
set.seed(123)
sample_a = tibble(sample = "a",
height = rnorm(20, mean = 0.1, sd = 0.01),
width = rnorm(20, mean = 50, sd = 10)) %>%
pivot_longer(c(height, width), names_to = "parameter", values_to = "result")
set.seed(321)
sample_b = tibble(sample = "b",
height = rnorm(20, mean = 0.2, sd = 0.03),
width = rnorm(20, mean = 55, sd = 10)) %>%
pivot_longer(c(height, width), names_to = "parameter", values_to = "result")
data = bind_rows(sample_a, sample_b)
当我绘制直方图时,当样本计数绘制在 y 轴上时,我能够比较每个样本中每个感兴趣参数的大小和变异性:
data %>%
ggplot()+
geom_histogram(aes(x = result))+
facet_grid(sample~parameter, scales = "free_x")
但是,当我使用
geom_density
(甚至合并y = after_stat(count)
,如本答案中所建议:将R ggplot中直方图中的y轴标准化为比例)时,幅度有很大不同:
data %>%
ggplot()+
geom_density(aes(x = result, y = stat(count)))+
facet_grid(sample~parameter, scales = "free_x")
如何使用平滑直方图在多面图中显示这些不同大小的结果?
ggplot(data, aes(x = result)) +
geom_density(aes(y = after_stat(scaled))) +
facet_grid(sample~parameter, scales = "free_x")
创建于 2023-11-01,使用 reprex v2.0.2