使用ggplot2在r中聚集条形图

sta*_*ser 7 r ggplot2

剪切我的数据框是

基本上我想显示按国家/地区分组的条形图,即我想在集群情节中显示没有人为所有国家做自杀事件,同样也是事故和刺伤.我正在使用ggplot2.我不知道如何去做这个.

任何帮助.

提前致谢

ale*_*han 9

编辑以更新较新的(2017)包版本

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")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

原始答案

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')
Run Code Online (Sandbox Code Playgroud)

我想这是你想要的格式?

ggplot(dat.m, aes(variable, value)) + 
  geom_bar(aes(fill = country), position = "dodge")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


MrG*_*ble 5

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='')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述