Plot grid histograms with fixed Y-axis - R

Asked

Viewed 210 times

5

I would like to plot two (or more) histograms in R where the Y axis prevails a global value for all histograms. I don’t want overlapping histograms, I want overlapping histograms. The more histogram I am, adding (right) the Plot and all with the same Y axis, because I need to compare them.

For example, in this image: inserir a descrição da imagem aqui

1 answer

4


See if the codes below help you.

I created three samples x, y and z, each with different normal distributions, and plotted one next to the other. Note that I first created x and y, just to add z. Note also that the function facet_grid does not require any parameter to leave the y axes on the same scale.

# dados originais

n <- 1000
x <- rnorm(n, mean=5, sd=3)
y <- rnorm(n, mean=0, sd=1)

dados <- data.frame(grupos=rep(c("x", "y"), each=n), valores=c(x,y))

ggplot(dados, aes(x=valores)) +
  geom_histogram(bins=30) +
  facet_grid(~ grupos)

inserir a descrição da imagem aqui

# adicionando outro grupo

z <- rnorm(n, mean=10, sd=2)
z <- data.frame(grupos="z", valores=z)

dados <- rbind(dados, z)

ggplot(dados, aes(x=valores)) +
  geom_histogram(bins=30) +
  facet_grid(~ grupos)

inserir a descrição da imagem aqui

If you want to leave the x axes all on the same scale, just rotate the code below, with the option scales = "free_x" inside facet_grid:

ggplot(dados, aes(x=valores)) +
  geom_histogram(bins=30) +
  facet_grid(~ grupos, scales = "free_x")

inserir a descrição da imagem aqui

  • PERFECT @!!!

  • if I want to divide by line, 5 Plots. How would it look? In this case, I have 10 histograms, and I want each row to stay with 5.

  • Substitute facet_grid(~ grupos) for facet_wrap(~ grupos, nrow=2).

  • Perfect! Vlw..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.