How do i put a barplot on top of another graph in r

Viewed 39

I have encountered a problem while trying to create a graph, that will look like this image:desired image

This image s made of a barplot on top of a points plot. I tried to place these two on top of each other using par(fig), but instead of getting the desired outcome, I just get them written over each other, or one of them overwritten by the other.

Here is my code:

y1=rnorm(1000, mean=0, sd=1)
y2=rnorm(1000, mean=0, sd=1)

y=hist(y1, freq=TRUE, breaks=100)
dev.off()

par(fig=c(1,0,1,0.75),mar=c(3,0,4,0), font.axis=2,
     cex.axis=1.1, cex.sub=1.1, crt=90)
plot(y1,y2, type="n", xlim=c(-3,3),ylim=c(-3,3), ann=FALSE)
points(y1,y2, pch=21, bg="red")


par(new=TRUE, fig=c(1,0.75,0,1),mar=c(3,0,4,0), font.main=2, font.sub=2, cex.main=1.1)
barplot(y$density, axes=FALSE, horiz=FALSE, ylim=c(0,0.6), 
        space=5, ann=FALSE)
title("Hustota normálního rozdělení", side = 3, line = 2)
mtext("(generováno 1000 čísel s parametry sigma=0, -1)",
      side = 3, line = 1)

I do not know if there are mistakes in my code or if this method just won't work. I am a begginer, so I apologize if my question is dumb.

Thanks for the help in advance

1 Answers

It's beautiful, just your par's were a bit off. Try this:

par(fig=c(0,1,0,.75),mar=c(3,1,4,1), font.axis=2,
    cex.axis=1.1, cex.sub=1.1, crt=90)
plot(y1,y2, type="n", xlim=c(-3,3),ylim=c(-3,3), ann=FALSE)
points(y1,y2, pch=21, bg="red")


par(new=TRUE, fig=c(0,1,.415,1),mar=c(3,1,4,1), font.main=2, font.sub=2, cex.main=1.1)
barplot(y$density, axes=FALSE, horiz=FALSE, ylim=c(0,0.6), 
        space=5, ann=FALSE)
mtext("Hustota normálního rozdělení", side = 3, line = 2)
mtext("(generováno 1000 čísel s parametry sigma=0, -1)",
      side = 3, line = 1)

enter image description here

Related