2017-02-18 148 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")