2016-08-21 56 views
0

如何在R上使用ggplot2使用此數據創建分組條形圖?使用ggplot2在R上分組的條形圖

Person Cats Dogs 

Mr. A 3 1 

Mr. B 4 2 

因此,它表明,顯示每人擁有寵物的數量,用這個佈局Bar chart of pets

我有這個數據的文本文件,並使用read.delim閱讀上R.

文件

我已經使用這段代碼,但它不會產生我正在尋找的棒圖。

ggplot(data=pets, aes(x=Person, y=Cats, fill=Dogs)) + geom_bar(stat="identity", position=position_dodge()) 

我是新來的R,任何幫助將不勝感激。

在此先感謝。

回答

5

要爲分組柱狀圖中準備數據,使用reshape2melt()功能

一加載所需的軟件包

library(reshape2) 
    library(ggplot2) 

II。創建數據幀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 
    3 4 Mr.B  Dogs  2 

四,分組酒吧陰謀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()) 

仙劍之上,圖例標題取出,軸標題刪除,調整欄寬度和酒吧之間的空間。

enter image description here