user330
user330

Reputation: 1290

Plotting barplots using three categorical variables in R

My data frame is similar to this

df<-read.table (text=" Gender   Fruit   Food
Male    Pear    Yes
Female  Pear    Yes
Male    Grape   Yes
Female  Apple   No
Male    Grape   No
Male    Pear    No
Male    Guba    Yes
Male    Grape   No
Female  Apple   No
Female  Pear    Yes
Female  Apple   Yes
Male    Guba    No
Female  Guba    No
Male    Pear    Yes
Male    Apple   Yes
Male    Pear    No
Female  Pear    Yes
Male    Guba    No

", header=TRUE)

I want to get a barplot like this along with a table under this plot to show numbers:

enter image description here

In plot G, A, G, P should read Grape, Apple, Guba and Pear

It would be good if we could have a table under this plot to see the values. This has been done in Excel simply.

Upvotes: 3

Views: 5008

Answers (2)

Alexlok
Alexlok

Reputation: 3134

With ggplot you need to map each of your variables of interest to an aesthetic or a facet. So something like that could work:

ggplot(df) +
  geom_bar(aes(x=Fruit, fill=Food),
           position = "dodge") +
  facet_wrap(~Gender)

barplot with counts along 3 variables

To add the table, you can simply compute it separately, then convert it to a graph element.

p_grph <- ggplot(df) +
  geom_bar(aes(x=Fruit, fill=Food),
           position = "dodge") +
  facet_wrap(~Gender)

p_table <- df %>%
  group_by(Gender, Fruit, Food) %>%
  summarize(count=n()) %>%
  gridExtra::tableGrob()

gridExtra::grid.arrange(p_grph, p_table)

plot on top and table below

Upvotes: 5

Duck
Duck

Reputation: 39613

You can also try:

library(ggplot2)
library(dplyr)
#Code
df %>% group_by_all() %>% summarise(N=n()) %>%
  ggplot(aes(x=Fruit,y=N,fill=Fruit))+
  geom_bar(stat = 'identity',
           position = position_dodge2(0.9,preserve = 'single'))+
  facet_wrap(Gender~Food,scales = 'free',nrow = 1)+
  theme(legend.position = 'top')

Output:

enter image description here

If you want to add a table, you can use patchwork:

library(patchwork)
#Data for table
Tab <- df %>% group_by_all() %>% summarise(N=n()) 
#Code
G1 <- df %>% group_by_all() %>% summarise(N=n()) %>%
  ggplot(aes(x=Fruit,y=N,fill=Fruit))+
  geom_bar(stat = 'identity',
           position = position_dodge2(0.9,preserve = 'single'))+
  facet_wrap(Gender~Food,scales = 'free',nrow = 1)+
  theme(legend.position = 'top')
#Compose
G1+gridExtra::tableGrob(Tab)

Output:

enter image description here

If you want the table below, you can change + by /.

Upvotes: 1

Related Questions