Grouped bar chart on R using ggplot2

匿名 (未验证) 提交于 2019-12-03 00:44:02

问题:

How do I create a grouped bar chart on R using ggplot2 using this data?

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.

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.

Thanks in advance.

回答1:

To prepare data for grouped bar plot, use melt() function of reshape2 package

I. Loading required packages

    library(reshape2)     library(ggplot2) 

II. Creating data frame 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

    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     3 4   Mr.B     Dogs     2 

IV. Grouped Bar plot by 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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!