How to Draw Grouped Barplot in R

When a variable has a few values, a frequency table, which may be displayed using a bar chart or barplot in R, is commonly used to summarise the data.

We’ll go over the fundamentals of making bar charts in R in this article.

A grouped barplot is a chart that shows amounts for multiple variables that have been grouped by another variable.

Wilcoxon Signed Rank Test in R » an Overview » finnstats

Using the data visualization tool ggplot2, this tutorial shows how to make grouped bar plots in R.

Draw grouped barplot in r ggplot2

Consider the following data frame, which shows the average number of points scored per game by nine basketball players:

make a data frame

df <- data.frame(team=rep(c('A', 'B', 'C'), each=3),
                 position=rep(c('Q1', 'Q2', 'Q3'), times=3),
                 points=c(24, 38, 48, 56, 13, 37, 87, 62, 45))

Let’s view the data frame

df
   team position points
1    A       Q1     24
2    A       Q2     38
3    A       Q3     48
4    B       Q1     56
5    B       Q2     13
6    B       Q3     37
7    C       Q1     87
8    C       Q2     62
9    C       Q3     45

To construct a grouped barplot that displays the points achieved by each player, grouped by team and position, we can use the following code.

library(ggplot2)
ggplot(df, aes(fill=position, y=points, x=team)) +
  geom_bar(position='dodge', stat='identity')

Changing the Look of a Grouped Barplot

The title, axis labels, theme, and colors of the grouped barplot can easily be changed to suit our needs.

library(ggplot2)
ggplot(df, aes(fill=position, y=points, x=team)) +
  geom_bar(position='dodge', stat='identity') +
  theme_minimal() +
  labs(x='Team', y='Points', title='Avg. Points Scored by Position & Team') +
  theme(plot.title = element_text(hjust=0.5, size=20, face='bold')) +
  scale_fill_manual('Position', values=c('red', 'green', 'blue'))

Using one of the themes from the ggthemes collection, we can further tweak the appearance. For instance, we may utilize this library’s Wall Street Journal Theme.

#install.packages('ggthemes')
library(ggplot2)
library(ggthemes)
ggplot(df, aes(fill=position, y=points, x=team)) +
  geom_bar(position='dodge', stat='identity') +
  theme_wsj()

Principal Component Analysis in R » finnstats

You may also like...

2 Responses

  1. Because the admin of this site is working, no hesitation very soon it will be well-known, due to
    its feature contents.

  2. Wow a good deal of excellent knowledge.

Leave a Reply

Your email address will not be published. Required fields are marked *

4 × 3 =