Eisen
Eisen

Reputation: 1897

Graphing multiple histograms in one output in grid ggplot2

I have the following pseudocode where I want to plot multiple histograms in a 4x8 grid. The length of vector cols is 32.

When I run this code it doesn't plot anything.

How can I fix this? Do i need to do some sort of facet? Not sure how to proceed.

par(mfrow = c(4,8))

cols <- t$label

for (i in cols) {
  
  df |>
  dplyr::filter(label == i) |>
  dplyr::select(count_col) |>
  ggplot2::ggplot(ggplot2::aes(x = count_col)) +
  ggplot2::geom_histogram() +
  ggplot2::ggtitle(i)
}

Upvotes: 1

Views: 219

Answers (1)

George Savva
George Savva

Reputation: 5336

Yes, you can use a facet_wrap for this. Look at the toy example below:

library(ggplot2)
dat <- data.frame(y=rnorm(1000), x=sample(1:32,1000,TRUE))

ggplot(dat, aes(x=y)) + geom_histogram() + facet_wrap(~x, ncol=8)

enter image description here

Upvotes: 4

Related Questions