knaka knaka - 1 year ago 154
R Question

Grouped bar chart on R using ggplot2

How do I create a grouped bar chart on R using

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
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.

Answer Source

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

I. Loading required packages


II. Creating data frame df

    df <- data.frame(Person = c("Mr.A","Mr.B"), Cats = c(3,4), Dogs = c(1,2))
    #   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')
    #   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 = 

Legend on top, legend title removed, axis titles removed, adjusted bar widths and space between bars.

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download