Search code examples
rplotkernel-density

Can I rotate a graph and plot it on the y axis?


I want to plot my points on a graph and then show the density distribution on the x-axis and on the y-axis at the same time. I'm able to do it on the x axis but not on the y axis.

par(mfrow=c(1,1))
plot(rnorm(100))
par(new=TRUE)
plot(density(rnorm(100,10,123)), ann = FALSE, xlab = "", ylab ="",xaxt='n', yaxt='n')

par(new=TRUE)
plot(density(rnorm(100, 10,12)), col = "red", ann = FALSE, xlab = "", ylab ="",xaxt='n', yaxt='n')

enter image description here


Solution

  • There is no reason you can't.

    set.seed(0)
    d1 <- density(rnorm(100, 10, 123))
    d2 <- density(rnorm(100, 10, 130))
    
    ## shared x, y, range / limit
    xlim <- c(min(d1$x[1], d2$x[1]), max(d1$x[512], d2$x[512]))  ## default: n = 512
    ylim <- c(0, max(d1$y, d2$y))
    
    ## conventional plot
    plot(d1$x, d1$y, type = "l", xlim = xlim, ylim = ylim)
    lines(d2$x, d2$y, col = 2)
    

    enter image description here

    ## rotated plot
    plot(d1$y, d1$x, type = "l", xlim = ylim, ylim = xlim)
    lines(d2$y, d2$x, col = 2)
    

    enter image description here

    Remarks:

    1. never use par(new = TRUE); set xlim and ylim yourself;
    2. customize the plot with title, axis display yourself.