Plot grid histograms with fixed Y axis - R

5

I would like to plot two (or more) histograms in R where the Y axis prevails a global value for all histograms. I do not want overlapping histograms, but rather side by side. The more histogram I am, it adds (to the right) of the plot and all with the Y axis equal, because I need to compare them.

As for example, in this image:

    
asked by anonymous 05.06.2017 / 18:56

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 next to each other. Note that I first created x and y , only to then add z . Note also that the facet_grid function does not require any parameters 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)

#adicionandooutrogrupoz<-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)

Ifyouwanttoleavethexaxesallonthesamescale,justrunthecodebelowwiththeoptionscales="free_x" within facet_grid :

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

    
05.06.2017 / 19:22