首页 > 解决方案 > 在 geom_smooth 图中包含变量分布

问题描述

使用 ggplot,我想创建一个我拥有的图,使用相同的 y 轴:

我已将 geom_histogram 添加到绘图中,但这会改变我的 ylim。但是,我不想改变 ylim,而是希望对其进行调整,使其适合绘图的 ylim,如果它只使用 geom_smooth。(在这种情况下,我猜应该是 ylim = c(0, 110))

set.seed(1)
age <- as.integer(runif(10000, 18, 80))
y <- rnorm(10000, 100, 10)
y2 <-  rnorm(10000, 50, 5)

 data <- data.frame(age, y, y2)

plot_data <- data %>% select(age, y, y2) %>% gather("type", "value", 2:3)

g <- ggplot(plot_data, mapping = aes_string(x = 'age', y = 'value', 
color='type')) + 
  geom_smooth() + 
  scale_x_continuous(labels = scales::comma) + 
  geom_histogram(inherit.aes=F, mapping = aes_string(x='age'), alpha=0.5)
# which would have show the count of the variable of the x-axis (age here) and would have max(count) = max(value)

g

标签: rggplot2

解决方案


您可以使用..count..拉出每个 bin 中的点数并将其缩放 的最大值value。Y 会变成count * max(value)/max(count)

ggplot(data = plot_data, aes(x = age)) + 
  geom_smooth(aes(y = value, color = type)) +
  scale_x_continuous(labels = scales::comma) +
  geom_histogram(aes(y =..count.. * (max(plot_data$value) / max(..count..))), alpha=0.5)

推荐阅读