0

I have the following code - the dataset results in 78 stacked bars. Does ggplot have a way to break on, say 8 bars per graph? I could break up the dataframe via loop but that seems pretty inefficient.

TTM <- read.csv("c:/temp/out.csv", header=TRUE)

library(ggplot2)

ggplot(data = TTM, aes(x = MTF, y = FTE, fill = Job)) +     
geom_bar(stat="identity")
Sathish
  • 12,453
  • 3
  • 41
  • 59

1 Answers1

1

Since you didn't provide any sample data, I'll use a built in dataset mtcars. Expanding on my comment above you could create a new group variable that has the number of groups you want. Using this you can do 1 of 3 things: (1) Facet_wrap, (2) grid.arrange, or (3) new pages

Data setup:

group.len <- 8
map <- data.frame(hp = unique(mtcars$hp), 
                  new_group = rep(1:ceiling(length(unique(mtcars$hp))/group.len), each = group.len, 
                                  length.out = length(unique(mtcars$hp))))

df <- merge(mtcars, map)

Facet wrap:

ggplot(data = df, aes(x = cyl, y = mpg, fill = as.factor(hp))) +     
  geom_bar(stat="identity") + facet_wrap(~new_group)

enter image description here

Grid.arrange:

I use the same exact approach as in this post place a legend for each facet_wrap grid in ggplot2. The original was about getting different legends for each facet, but I think it's also very applicable to your problem:

library(gridExtra)
out <- by(data = df, INDICES = df$new_group, FUN = function(m) {
  m <- droplevels(m)
  m <- ggplot(m, aes(as.factor(cyl), mpg, fill = as.factor(hp))) + 
    geom_bar(stat="identity")
})
do.call(grid.arrange, out)

enter image description here New pages:

Note this uses the out object from grid.arrange. This will put each plot on a new page (instead of all on one page like in grid.arrange.

lapply(out, function(x) {x})
Community
  • 1
  • 1
Mike H.
  • 13,960
  • 2
  • 29
  • 39