Freya
Freya

Reputation: 159

How do I get rid of the empty bar charts in a faceted plot?

I am experiencing a problem with the facet_grid function in R. My own experimental design is somewhat complex and hard to explain, but I created a fake data set that is structurally similar to what I am doing, so I hope it will be helpful.

Suppose we have done a silly experiment where we asked 10 people to rate 2 kinds of fruit and 2 kinds of vegetable, by asking them whether they liked these foods or not. So the response variable is binary. The following code generates my fake data set, and draws the graphs that I want.

But there is a problem. Each panel created by facet_grid contains all kinds of food - but since this is a nested design and all data points for Apple and Pear only fall under the category "Fruit" and data points for Broccoli and Cabbage fall under the category "Vegetable", we end up getting "empty bars".

Is there a way for me to get rid of them?

I want to have two panels broken down by Food (i.e., Fruit vs. Vegetable) and I want each panel to show only two bar charts (the left one showing Apple and Pear, the right one showing Broccoli and Cabbage). How can I modify my code to do this?

Food <- rep(c("Fruit", "Vegetable"), each=20)
Food

Kind <- rep(c("Apple", "Pear", "Broccoli", "Cabbage"), each=10)
Kind

Rating <- rep(c("Like", "Dislike"), each=20)
Rating

set.seed(111)

Rating <- sample(Rating, 40, replace=FALSE)
Rating

FoodRatings <- cbind(Food, Kind, Rating)

FoodRatings <- as_data_frame(FoodRatings)

ggplot(data=FoodRatings) + geom_bar(aes(x=Kind, fill=Rating)) +facet_grid(~Food)

Upvotes: 1

Views: 39

Answers (1)

Iroha
Iroha

Reputation: 34761

You can use the scales argument in facet_grid():

ggplot(data=FoodRatings) +
 geom_bar(aes(x=Kind, fill=Rating)) +
 facet_grid(~Food, scales = "free_x")

enter image description here

Upvotes: 2

Related Questions