2017-02-18 122 views
-3

我有一個數據幀,如下所示:R:ggplot箱形圖

Calories Protein TotalFat 
1  717 0.85 81.11 
2  717 0.85 81.11 
3  876 0.28 99.48 
4  353 21.40 28.74 
5  371 23.24 29.68 
6  334 20.75 27.68 
7  300 19.80 24.26 
9  403 24.90 33.14 
11  394 23.76 32.11 
12  98 11.12  4.30 

我想使一個boxplot使用ggplot。我可以用下面的代碼

boxplot(df) 

做到這一點使用基礎R但我怎麼做ggplot

+0

也許你可以先從'?? geom_boxplot'手冊中找到一些例子嗎? http://docs.ggplot2.org/0.9.3.1/geom_boxplot.html – zx8754

+0

本文沒有我要找的內容。 –

+3

您必須將數據從寬格式轉換爲長格式:'library(tidyverse); df%>%gather()%>%ggplot(aes(key,value))+ geom_boxplot()'。 – lukeA

回答

0

要使用ggplot,你應該從重塑全格式的數據長的格式,以便它看起來像這樣:

library(tidyverse) 
df %>% gather %>% head(20) 
#   key value 
# 1 Calories 717.00 
# 2 Calories 717.00 
# ... 
# 11 Protein 0.85 
# 12 Protein 0.85 
# ... 

你可以做

df %>% 
    gather %>% 
    ggplot(aes(key, value)) + 
    geom_boxplot() 

...並獲得:

enter image description here

Data:

df <- read.table(header=T,text=" Calories Protein TotalFat 
1  717 0.85 81.11 
2  717 0.85 81.11 
3  876 0.28 99.48 
4  353 21.40 28.74 
5  371 23.24 29.68 
6  334 20.75 27.68 
7  300 19.80 24.26 
9  403 24.90 33.14 
11  394 23.76 32.11 
12  98 11.12  4.30")