0

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

M. Beausoleil
  • 3,141
  • 6
  • 29
  • 61
  • I've tried this: ```par(mfrow=c(1,1), bg = "white") plot(rnorm(100)) par(new=TRUE) plot(density(rnorm(100,10,123)), ann = FALSE, xlab = "", ylab ="",xaxt='n', yaxt='n') d = density(rnorm(100, 10,12)) par(new=TRUE, bg=NA) plot(d$y,d$x, type = "l", col = "red", ann = FALSE, xlab = "", ylab ="",xaxt='n', yaxt='n', bty='n)```, but it's not printing the graph under it... – M. Beausoleil Dec 05 '16 at 20:26

1 Answers1

2

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.
Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
  • But I want to plot the points at the same time. The focus should be on the points. The scale is so large for the density distribution compared to the points that I have to set the limits super large – M. Beausoleil Dec 05 '16 at 20:35