[英]Grouped bar chart on R using ggplot2
How do I create a grouped bar chart on R using ggplot2
using this data?如何使用此数据使用
ggplot2
在 R 上创建分组条形图?
Person Cats Dogs
Mr. A 3 1
Mr. B 4 2
So that it shows that shows number of pets owned per person, with this layout Bar chart of pets以便它显示显示每人拥有的宠物数量,带有宠物的布局条形图
I have a text file with this data and have used read.delim
to read the file on R.我有一个包含这些数据的文本文件,并使用
read.delim
读取 R 上的文件。
I have used this code but it does not produce the bar plot I am looking for.我已经使用了这段代码,但它没有产生我正在寻找的条形图。
ggplot(data=pets, aes(x=Person, y=Cats, fill=Dogs)) + geom_bar(stat="identity", position=position_dodge())
I am new to R, any help would be appreciated.我是 R 的新手,任何帮助将不胜感激。
Thanks in advance.提前致谢。
To prepare data for grouped bar plot, use melt()
function of reshape2
package要为分组条形图准备数据,请使用
reshape2
包的melt()
函数
I. Loading required packages一、加载需要的包
library(reshape2)
library(ggplot2)
II.二、 Creating data frame
df
创建数据框
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
III.三、 Melting data using
melt
function使用
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.四、 Grouped Bar plot by
Person
按
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())
Legend on top, legend title removed, axis titles removed, adjusted bar widths and space between bars.图例在顶部,图例标题已删除,轴标题已删除,调整了条形宽度和条形间距。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.