2016-06-08 320 views
2

x軸考慮簡單的例子:註釋文本使用GGPLOT2

library(ggplot2) 

head(mtcars) 


# create the plot 
ggplot(mtcars, aes(factor(cyl))) + geom_bar() + theme_bw() + 
     theme(strip.text.x = element_text(size = 20, face="bold"))+ 
     xlab("number of cyl") + ylab("Count") 

現在我們可以得到平均$mpgcyl有:

aggregate(mpg ~ cyl, data = mtcars, FUN=mean) 

我怎樣才能把這些平均值爲X以使它們出現在對應的cyl之下。一個可以繪製表格,不知怎麼寫,這是每缸的......平均MPG ...

+1

也許這會有所幫助:http://stackoverflow.com/questions/16680063/how-can-i-add-a-table-to-my-ggplot2-output – beetroot

+0

是否有使用特定的原因'facet_grid'代替'ggtitle()'在劇情上放置一個標題?這可能會給潛在的答案增加不必要的複雜性。 – Uwe

+0

不,讓我們刪除它 – user08041991

回答

1

這裏有一個簡單的方法通過重寫因子水平的名稱做到這一點:

(注意,這是安全只有aggregate以與因子等級名稱相同的順序生成表格並且沒有任何差距 - 這看起來應該是這種情況,但必須進行調查以確保它的安全。將它編碼爲一個循環,並期待在級別名稱,以確保它們能夠正確匹配)

library(ggplot2) 

head(mtcars) 

adf <- aggregate(mpg ~ cyl, data = mtcars, FUN=mean) 
mtcars$fcyl <- factor(mtcars$cyl) 
levels(mtcars$fcyl) <- sprintf("%d \n %.1f",adf$cyl,adf$mpg) 

# create the plot 
ggplot(mtcars, aes(fcyl)) + geom_bar() + theme_bw() + 
    theme(strip.text.x = element_text(size = 20, face="bold"))+ 
    xlab("number of cyl") + ylab("Count") 

產生:

enter image description here

+0

謝謝。任何意見? –