Grouped bar chart on R using ggplot2

寵の児 提交于 2019-12-04 20:06:04

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.

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