Wish to move from grid.arrange to ggplot2 facet_grid

Hi,

I wish to plot 7 barcharts next to each other using a ggplot2 facet grid (I believe this to be correct).

I have managed to come up with a solution by utilising the grid.arrange package, however the code is bloated and repeats itself:

var1<- ggplot(df, aes(var1)) + geom_bar(stat="count")
var2<- ggplot(df, aes(var2)) + geom_bar(stat="count")
var3<- ggplot(df, aes(var3)) + geom_bar(stat="count")
var4<- ggplot(df, aes(var4)) + geom_bar(stat="count")
var5<- ggplot(df, aes(var5)) + geom_bar(stat="count")
var6<- ggplot(df, aes(var6)) + geom_bar(stat="count")
var7<- ggplot(df, aes(var7)) + geom_bar(stat="count")

grid.arrange(var1, var2, var3, var4, var5, var6, var7, ncol = 4, nrow = 2)

This code produces 7 separate barcharts and places them in a 2 x 4 grid.

As mentioned, this code seems far from efficient.

I have tried playing around with ggplot2 facet_grid but I can't seem to get it to work how I want. As all the online videos/forum posts state that you need to define x/y. But I want the Y axis to be the count of each column and X to be going from 1 to 7, as per the ranking (In my data, the numbers represent ordinal data. As each var was ranked against the other, with 1 being the highest)

The following produces one barchart:

ggplot(df, aes(x = var1)) + 
  geom_bar(stat="count") +
  facet_grid()

I understand this is due to only specifying one column, however I'm not sure how to add the other columns so it produces multiple charts. Also, I have no clue what I would put in the facet_grid() argument.

Example of my data:
pic

In my data, the numbers represent ordinal data. As each var was ranked against the other, with 1 being the highest.

"sex" is in there, however I do not want to use that in the facet_grid() argument. It can be ignored.

Apologies if I'm just completely misunderstanding things, I just feel at a loss after hours of trying to get this to work.

For face_grid() to work you need to reshape your data frame into a long format, you dan do it with the tidyr::pivot_longer() function.

If you need more specific help, please provide a proper REPRoducible EXample (reprex) illustrating your issue. (we can't copy sample data from a screenshot).

Ah I can't thank you enough! It's been about 3 years since I've done any analysis, so I'm slowly brushing the dust off.

For reference, the following code worked for me:

measures_long <- 
  pivot_longer(measures, c(2:8), 
               names_to = "Measure", 
               values_to = "Rank")

ggplot(measures_long, aes(Rank)) +
  geom_bar(stat="count") +
  facet_grid(~Measure)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.