如何ggplot2
使用此数据在R上创建分组条形图?
Person Cats Dogs
Mr. A 3 1
Mr. B 4 2
这样就可以显示每人拥有的宠物数量,以及该布局的宠物条形图
我有一个包含此数据的文本文件,并曾经read.delim
在R上读取该文件。
我已经使用了此代码,但是它不会产生我要查找的条形图。
ggplot(data=pets, aes(x=Person, y=Cats, fill=Dogs)) + geom_bar(stat="identity", position=position_dodge())
我是R的新手,我们将不胜感激。
提前致谢。
要准备分组条形图的数据,请使用包的melt()
功能reshape2
I.加载所需的程序包
library(reshape2)
library(ggplot2)
二。创建数据框df
df <- data.frame(Person = c("Mr.A","Mr.B"), Cats = c(3,4), Dogs = c(1,2))
df
# Person Cats Dogs
# 1 Mr.A 3 1
# 2 Mr.B 4 2
三,使用melt
功能融合数据
data.m <- melt(df, id.vars='Person')
data.m
# Person variable value
# 1 Mr.A Cats 3
# 2 Mr.B Cats 4
# 3 Mr.A Dogs 1
# 4 Mr.B Dogs 2
IV。按条形图分组Person
ggplot(data.m, aes(Person, value)) + geom_bar(aes(fill = variable),
width = 0.4, position = position_dodge(width=0.5), stat="identity") +
theme(legend.position="top", legend.title =
element_blank(),axis.title.x=element_blank(),
axis.title.y=element_blank())
图例位于顶部,图例标题已删除,轴标题已删除,调整的条宽度和条之间的间距。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句