使用ggplot2在r中绘制分组条形图

10

我有一个数据框,其中包含一些数据。

我想展示按国家分组的条形图,即我想在簇状图中显示所有国家自杀人数、事故和刺伤的人数。我使用ggplot2进行绘制,但我不知道如何操作。

希望能得到帮助。

谢谢!


1
为了以后的参考,发布数据图像是在这里展示数据的最不有用的方法。看看如何制作可重复的示例https://dev59.com/eG025IYBdhLWcg3whGSx - 如果您使数据易于使用,您将获得更多帮助。 - alexwhan
2个回答

13

编辑以更新到较新的(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")

在这里输入图片描述

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')

我猜这就是你想要的格式?

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

在此输入图片描述


library(reshape) - Climbs_lika_Spyder
@Hack-R 检查一下你是否试图绘制一个因子。 - Climbs_lika_Spyder

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='')

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接