r - 在 geom_smooth 图中包含变量分布
问题描述
使用 ggplot,我想创建一个我拥有的图,使用相同的 y 轴:
geom_smooth 线(应在其上调整轴)
geom_histogram(x 变量的分布)
我已将 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
解决方案
您可以使用..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)
推荐阅读
- reactjs - React - 使用 Auth0 进行不和谐身份验证
- java - 程序的“安全/锁定窗口”,Windows 10
- python - Python pandas drop_duplicates() 不准确
- firebase - 如何将 Firestore 文档 ID 编组到结构中?
- c - 使用clang for if条件编译错误
- r - 在 R 中动态命名对象
- xml - 使用尽可能少的硬编码将 XML 文件解析为 CSV
- editor - Elliot 在第 4 季第 8 集(机器人先生)中使用了什么编辑器?
- ios - 有没有办法让 iOS 模拟器访问重定向到我的本地主机的 FQDN?
- python-3.x - 将列表打印到数组,但始终在列表中再打印 1 个项目