R语言 更改密度图的x或y位置

eqqqjvef  于 2023-06-03  发布在  其他
关注(0)|答案(1)|浏览(163)

我有数据绘制为点,并希望添加密度图的图形。ggExtra或其他软件包的边际图解决方案没有给我想要的自由,所以我想在ggplot的同时生成密度图。

df = data.frame(x = rnorm(50, mean = 10), 
                y = runif(50, min = 10, max = 20), 
                id = rep(LETTERS[1:5], each = 10))
ggppp = ggplot(data = df, mapping = aes(x, y, color = id)) + 
  geom_point() + theme_bw()

ggppp + 
  geom_density(mapping = aes(y = y, 
                             col = id),
               inherit.aes = FALSE, bounds = c(-Inf, Inf)) +
  geom_density(mapping = aes(x = x,
                             col = id),
               inherit.aes = FALSE, )

是否有方法将密度图移动到其他x或y位置值(如将密度线移动到下图中箭头的尖端)?

sulc1iza

sulc1iza1#

你可以用position_nudge移动位置:

## using your example objects:
ggppp + 
  geom_density(mapping = aes(y = y , col = id),
               position = position_nudge(x = 12),
               inherit.aes = FALSE
               ) +
  geom_density(mapping = aes(x = x, col = id),
               position = position_nudge(y = 20),
               inherit.aes = FALSE
)

相关问题