使用 ggplot2 绘制 CSV 数据的箱线图

Boxplot of CSV data with ggplot2

我有一个 CSV 文件,其中包含六个月(2016 年 8 月 - 2017 年 1 月)每天的体重。我想为每个月绘制一个箱线图,基本上绘制每个月数据的 summary() 。我想为它使用 ggplot2,因为它看起来更漂亮。我四处寻找解决方案并提出了很多但似乎没有解决我想要的问题。

数据的头部和摘要:

> wts <- read.csv('weights.csv', header=T, sep=',')
> head(wts)
  August.2016 September.2016 October.2016 November.2016 December.2016 January.2016
1       254.2          250.0        248.2         245.8         245.6        244.4
2       252.6          249.2        248.6         246.4         246.0        245.0
3       251.8          250.6        249.2         248.0         246.4        244.3
4       253.2          252.4        249.8         247.5         246.0        243.6
5       252.2          250.6        248.8         247.0         246.0        242.6
6       254.0          251.0        247.8         247.6         246.0        242.0
> summary(wts)
  August.2016    September.2016   October.2016   November.2016   December.2016    January.2016  
 Min.   :249.6   Min.   :245.6   Min.   :245.4   Min.   :244.2   Min.   :243.4   Min.   :241.6  
 1st Qu.:252.2   1st Qu.:248.3   1st Qu.:246.7   1st Qu.:246.2   1st Qu.:244.8   1st Qu.:242.9  
 Median :252.8   Median :249.2   Median :247.8   Median :246.6   Median :245.6   Median :243.6  
 Mean   :252.7   Mean   :249.1   Mean   :247.6   Mean   :246.7   Mean   :245.3   Mean   :243.5  
 3rd Qu.:253.6   3rd Qu.:250.0   3rd Qu.:248.2   3rd Qu.:247.2   3rd Qu.:246.0   3rd Qu.:244.3  
 Max.   :255.2   Max.   :252.4   Max.   :249.8   Max.   :248.6   Max.   :247.0   Max.   :245.0  
                 NA's   :1                       NA's   :1                       NA's   :1  

根据我收集到的信息,我需要以 ggplot 喜欢的方式重塑数据,但我不确定该怎么做。如果可能的话,我还想在箱线图上突出显示平均值(带有实际数字)。我能知道怎么做吗?

谢谢

要保持​​相同的范例,您可以使用 tidyr 包中的 gather() 将数据重塑为长格式,并将结果插入 ggplot()。要添加描述均值的文本,您可以将 stat_summary()"text" geom 一起使用,并将 mean 函数应用于 value 变量。

library(tidyr)
library(ggplot2)

ggplot(gather(wts, factor_key = TRUE), 
   aes(key, value)) + 
    geom_boxplot() + 
    stat_summary(aes(label = ..y..), 
                 fun.y = function(x) round(mean(x), 2), 
                 geom = "text", 
                 size = 3,
                 color = "red")