how to make a grouped bar plot?



culture=matrix(c(7.70,7.36,6.38,6.39,6.43,5.69), nrow=2, byrow = TRUE)
colnames(culture)= c("cananda","United States","France")

   cananda United States France

Female 7.70 7.36 6.38
male 6.39 6.43 5.69

So I want to make a barplot with this data.

But when I try


R shows a stacked bar graph.

I want to make it grouped bar graph so that I can compare.

How do I make it?


Hey @VirginTechnician! You nearly got it right formatting your code: you want to use triple backticks (on a US keyboard, the backtick is the key to the left of the 1 key and above the TAB key), rather than three apostrophes. But you have the right idea :wink:

When you say a 'grouped' barplot, what did you have in mind? Did you mean having 'clusters' of bars, like the plot in this SO answer (or the clustered column chart in Excel)?

I can't help you plot this in base R (which is the system used by barplot(), but I can help you do it with ggplot2. The first thing you'll need to do is tidy your data. Right now, you have two variables (country and gender), leading to six categories. Instead of having a column for each 'series', or category, (Male/US, Female/US, Male/Canada, …), you'll want to have each column describe the value for each variable. So your data could look like this:


culture <-
  culture %>%
  as_data_frame(rownames = NA) %>%
  rownames_to_column(var = 'gender') %>%
  gather(key = 'country', value = 'value', -gender)
#> # A tibble: 6 x 3
#>   gender country       value
#>   <chr>  <chr>         <dbl>
#> 1 Female cananda        7.7 
#> 2 male   cananda        6.39
#> 3 Female United States  7.36
#> 4 male   United States  6.43
#> 5 Female France         6.38
#> 6 male   France         5.69

Now you can plot it with ggplot2 :slight_smile:

ggplot(culture) +
    aes(x = country, y = value, fill = gender),
    position = 'dodge')

Created on 2018-10-25 by the reprex package (v0.2.0).

(You can swap country and gender depending on how you want to group it!)


When using base barplot(), the key parameter that gives you a grouped plot instead of a stacked plot is beside = TRUE. This page has a good overview, with some helpful tips: