How to create grouped barplot with R [duplicate]

Welcome to SO.

You might want to look at ggplot2 , on Hadley’s page you will find detailed examples how to do it. Here’s an example:

# if you haven't installed ggplot, if yes leave this line out
install.packages("ggplot2") # choose your favorite mirror

# check the dataset
# plot it 
ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar(position="dodge") +
opts(title="Examplary Grouped Barplot")

enter image description here

What’s nice about the ggplot2 package is that you can change the visualization of some parameter (aesthetic,aes) easily. For example you could look into facects or stacked barcharts instead of grouping them. Plus, it’s well documented on Hadley’s page.

For the sake of completeness, here’s also a non ggplot2 example found @quickR

# Grouped Bar Plot
counts <- table(mtcars$vs, mtcars$gear)
barplot(counts, main="Car Distribution by Gears and VS",
xlab="Number of Gears", col=c("darkblue","red"),
 legend = rownames(counts), beside=TRUE)

enter image description here

Leave a Comment