3

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)?

zx8754
  • 52,746
  • 12
  • 114
  • 209
M. Beausoleil
  • 3,141
  • 6
  • 29
  • 61
  • Do you meant to increase the height of those density curves to cover the whole axis? Maybe you need to scale it before plotting. – zx8754 Jun 02 '23 at 12:59
  • 1
    Sorry for not being clear, no, I just want to 'raise' the density plot so that they don't 'sit' on x = 0 or y = 0, but that I could make the density plots on x = 13 or y = 20. Is that clearer? – M. Beausoleil Jun 02 '23 at 13:18
  • 1
    Have you seen the answers to this question: none directly address the requirement to place density plots within the plotting area but the packages listed may help: https://stackoverflow.com/questions/8545035/scatterplot-with-marginal-histograms-in-ggplot2 – Peter Jun 02 '23 at 14:03
  • I did see those. The problem is that when I want to customize a bit more, there are limitations. It was easier for me to find how to just move the density plot in a single ggplot graph. – M. Beausoleil Jun 02 '23 at 14:17

1 Answers1

4

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
)
Nate
  • 10,361
  • 3
  • 33
  • 40
I_O
  • 4,983
  • 2
  • 2
  • 15
  • 1
    We can replace `x = 12` and `y = 20` with `ceiling(max(df$x))` and `ceiling(max(df$y))` to make it more automated. – zx8754 Jun 02 '23 at 20:47