Reputation: 4180
Suppose I have two samples that I would like to compare graphically. One way to do it is to lay one over another like below:
x1 = rnorm(100)
x2 = rnorm(100, mean=2)
plot(density(x1))
lines(density(x2), col="red")
I wonder however if there is a way to plot x2 such that the plot shares the same axis as the plot of x1, except that it is upside down, like the plot below. It would be especially great if there is any method that does not involve downloading additional packages.
Thanks!
Upvotes: 0
Views: 4596
Reputation: 93
It is possible to get only one x-axis using the mar
argument of the par
function. The R code would look like this:
#Create Data
x1 = rnorm(100)
x2 = rnorm(100, mean=2)
#Make the plot
par(mfrow=c(2,1))
par(mar=c(0,5,3,3))
plot(density(x1) , main="" , xlab="", ylim=c(0,1) , xaxt="n", las=1 , col="slateblue1" , lwd=4 )
par(mar=c(5,5,0,3))
plot(density(x2) , main="" , xlab="Value of my variable", ylim=c(1,0) , las=1 , col="tomato3" , lwd=4)
Giving this plot:
This graph is present in the R graph gallery
Upvotes: 0
Reputation: 81733
If it doesn't matter if the y-axis contains values below zero, you can use this:
x1 <- rnorm(100)
x2 <- rnorm(100, mean=2)
dens1 <- density(x1)
dens2 <- density(x2)
dens2$y <- dens2$y * -1
plot(dens1,
ylim = range(c(dens1$y, dens2$y)),
xlim = range(c(dens1$x, dens2$x)),
main = "",
xlab = "")
lines(dens2, col = "red")
Upvotes: 4
Reputation: 179558
You can reverse the axis of a plot by using the argument ylim=(...)
(or xlim=(...)
) and specifying the limits in the reverse order.
For example:
layout(matrix(1:2, ncol=1))
par(mai=c(0.5, 1, 0.5, 1))
plot(c(-6, 6), 0:1, type="n", ylim=c(0, 1), xlab="", ylab="")
lines(density(x1), ylim=c(0, 1))
plot(c(-6, 6), 0:1, type="n", ylim=c(1, 0), xlab="", ylab="")
lines(density(x2), col="red", ylim=c(1, 0))
Upvotes: 3