Jim
Jim

Reputation: 725

Plot multiple histogram series in separate charts ggplot2

Here's my code:

#set parameters
p <- 0.41
n <- 100
s <- 200

#generate data
y_1_list = c()
for (i in 1:s){
  for (j in 1:n){
    vars[j] <- rbinom(1, 1, p)
  }
  y_1_list[i] <- sum(vars) / n
}

y_2_list = c()
for (i in 1:s){
  for (j in 1:n){
    vars[j] <- rbinom(1, 1, p)
  }
  y_1 <- sum(vars) / n
  y_2_list[i] <- sum(y_1 - vars)^2 / n
}

y_3_list = c()
for (i in 1:s){
  for (j in 1:n){
    vars[j] <- rbinom(1, 1, p)
  }
  y_1 <- sum(vars) / n
  y_3_list[i] <- y_1 / n
}

y_4_list = c()
for (i in 1:s){
  for (j in 1:n){
    vars[j] <- rbinom(1, 1, p)
  }
  y_1 <- sum(vars) / n
  y_4_list[i] <- y_1 / sqrt(n)
}

#bind vectors into data frame
samples <- data.frame(y_1_list, y_2_list, y_3_list, y_4_list)

#ggplot histograms
ggplot(data = samples, aes(y_1_list)) + 
  geom_histogram()

I'd like to plot four separate histograms, on a 2x2 grid, for each of these series: y_1_list, y_2_list, y_3_list, y_4_list.

The only resources I can find online are for more complicated plots: a) plot data from the same variable split by some other variable b) plot data on the same chart.

Upvotes: 0

Views: 1488

Answers (2)

shu251
shu251

Reputation: 251

In addition to below answer, you can also use facet_grid() in ggplot. Using facet_grid() or facet_wrap() is smoother, but if you need to add other types of graphs into the same figure or include a specific legend, I also use:

#Load library "gridExtra"
library(gridExtra)

#Plot graphs in 2x2:
grid.arrange(
  ggplot(data = samples, aes(y_1_list))+geom_histogram(),
  ggplot(data = samples, aes(y_2_list))+geom_histogram(),
  ggplot(data = samples, aes(y_3_list))+geom_histogram(),
  ggplot(data = samples, aes(y_4_list))+geom_histogram(),
   ncol=2)

Upvotes: 2

GL_Li
GL_Li

Reputation: 1798

Try to rebuild the data frame and use facet_wrap in ggplot

#bind vectors into data frame
samples <- data.frame(y = c(y_1_list, y_2_list, y_3_list, y_4_list), 
                      ylabel = rep(c("y1", "y2", "y3", "y4"), each = 200))

#ggplot histograms
ggplot(data = samples, aes(y)) + 
    geom_histogram() +
    facet_wrap(~ylabel, nrow = 2, scale = "free_x")

Upvotes: 1

Related Questions