stackoverflowuser
stackoverflowuser

Reputation: 262

Clustered Bar plot in r using ggplot2

Snip of my data frame is

Basically i want to display barplot which is grouped by Country i.e i want to display no of people doing suicides for all of the country in clustered plot and similarly for accidents and Stabbing as well.I am using ggplot2 for this.I have no idea how to do this.

Any helps.

Thanks in advance

Upvotes: 10

Views: 33738

Answers (2)

alexwhan
alexwhan

Reputation: 16026

Edit to update for newer (2017) package versions

library(tidyr)
library(ggplot2)
dat.g <- gather(dat, type, value, -country)
ggplot(dat.g, aes(type, value)) + 
  geom_bar(aes(fill = country), stat = "identity", position = "dodge")

enter image description here

Original Answer

dat <- data.frame(country=c('USA','Brazil','Ghana','England','Australia'), Stabbing=c(15,10,9,6,7), Accidents=c(20,25,21,28,15), Suicide=c(3,10,7,8,6))
dat.m <- melt(dat, id.vars='country')

I guess this is the format you're after?

ggplot(dat.m, aes(variable, value)) + 
  geom_bar(aes(fill = country), position = "dodge")

enter image description here

Upvotes: 13

MrGumble
MrGumble

Reputation: 5766

library(ggplot2)
library(reshape2)
df <- data.frame(country=c('USA','Brazil','Ghana','England','Australia'), Stabbing=c(15,10,9,6,7), Accidents=c(20,25,21,28,15), Suicide=c(3,10,7,8,6))
mm <- melt(df, id.vars='country')
ggplot(mm, aes(x=country, y=value)) + geom_bar(stat='identity') + facet_grid(.~variable) + coord_flip() + labs(x='',y='')

enter image description here

Upvotes: 5

Related Questions