Search code examples
rggplot2density-plot

Change x or y position of density plot


I have data plotted as points and would like to add density plots to the graph. The marginal plot solutions from ggExtra or other packages are not giving the freedom that I'd like and so want to generate the density plot at the same time as the 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, ) 

enter image description here

Is there a way to move the density plots to other values of x or y position (like moving the density lines to the tip of the arrow in the image below)?


Solution

  • you can shift the position with 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
    )