在geom_smooth图中包括变量分布

时间:2019-01-23 19:11:06

标签: r ggplot2

使用ggplot,我想使用相同的y轴创建其中的绘图:

  • geom_smooth线(应在其上调整轴)

  • geom_histogram(x变量的分布)

我已将geom_histogram添加到图中,但这改变了我的ylim。但是,我不想改变ylim,而是希望对其进行调整,以使其仅在使用geom_smooth时适合绘图的ylim。 (在这种情况下,我猜应该是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

1 个答案:

答案 0 :(得分:0)

您可以使用..count..提取每个仓中的点数,并按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)