如何使用 R 中的 ggplot2 在箱線圖中繪製均值?
當我們建立一個箱形圖時,它會顯示最小值、最大值、第一四分位數、中位數和第三四分位數,但我們可能還想要繪製均值,以便還可以根據均值來比較因子水平。要建立這種型別的繪圖,我們首先需要找到組均值,然後可以用 ggplot2 的 geom_text 函式使用該均值。
示例
考慮 basic R 中的 CO2 資料 -
> head(CO2,20) Plant Type Treatment conc uptake 1 Qn1 Quebec nonchilled 95 16.0 2 Qn1 Quebec nonchilled 175 30.4 3 Qn1 Quebec nonchilled 250 34.8 4 Qn1 Quebec nonchilled 350 37.2 5 Qn1 Quebec nonchilled 500 35.3 6 Qn1 Quebec nonchilled 675 39.2 7 Qn1 Quebec nonchilled 1000 39.7 8 Qn2 Quebec nonchilled 95 13.6 9 Qn2 Quebec nonchilled 175 27.3 10 Qn2 Quebec nonchilled 250 37.1 11 Qn2 Quebec nonchilled 350 41.8 12 Qn2 Quebec nonchilled 500 40.6 13 Qn2 Quebec nonchilled 675 41.4 14 Qn2 Quebec nonchilled 1000 44.3 15 Qn3 Quebec nonchilled 95 16.2 16 Qn3 Quebec nonchilled 175 32.4 17 Qn3 Quebec nonchilled 250 40.3 18 Qn3 Quebec nonchilled 350 42.1 19 Qn3 Quebec nonchilled 500 42.9 20 Qn3 Quebec nonchilled 675 43.9 > means <- aggregate(uptake ~ Treatment, CO2, mean) > means Treatment uptake 1 nonchilled 30.64286 2 chilled 23.78333
使用 Treatment 建立帶均值的箱線圖 -
> library(ggplot2) > ggplot(CO2,aes(Treatment,uptake))+geom_boxplot()+ + stat_summary(fun.y=mean,geom="point")+ + geom_text(data=means,aes(label=uptake))
輸出
使用 Type 建立帶均值的箱線圖 -
> means <- aggregate(uptake ~ Type, CO2, mean) > ggplot(CO2,aes(Type,uptake))+geom_boxplot()+ + stat_summary(fun.y=mean,geom="point")+ + geom_text(data=means,aes(label=uptake))
輸出
廣告