![](/img/trans.png)
[英]How to run and annotate separate TukeyHSD for individual facets in ggplot2 boxplot?
[英]annotate boxplot in ggplot2
我使用ggplot2創建了一個並排的boxplot。
p <- ggplot(mtcars, aes(x=factor(cyl), y=mpg))
p + geom_boxplot(aes(fill=factor(cyl)))
我想在圖中用min,max,1st quartile,median和3rd quartile進行注釋。 我知道geom_text()
可以這樣做,並且可能是fivenum()
是有用的。 但我無法弄清楚我到底能怎么做! 這些值應該顯示在我的圖中。
我能想到的最簡潔的方法是使用stat_summary
。 我還將標簽映射到顏色美學,但是如果您願意,您當然可以將標簽設置為單一顏色:
ggplot(mtcars, aes(x=factor(cyl), y=mpg, fill=factor(cyl))) +
geom_boxplot(width=0.6) +
stat_summary(geom="text", fun.y=quantile,
aes(label=sprintf("%1.1f", ..y..), color=factor(cyl)),
position=position_nudge(x=0.33), size=3.5) +
theme_bw()
在上面的代碼中,我們使用quantile
作為匯總函數來獲取標簽值。 ..y..
返回quantile
函數的輸出(通常, ..*..
是使用ggplot中計算的值的ggplot結構)。
一種方法是簡單地創建您需要的data.frame,並將其傳遞給geom_text
或geom_label
:
library(dplyr)
cyl_fivenum <- mtcars %>%
group_by(cyl) %>%
summarise(five = list(fivenum(mpg))) %>%
tidyr::unnest()
ggplot(mtcars, aes(x=factor(cyl), y=mpg)) +
geom_boxplot(aes(fill=factor(cyl))) +
geom_text(data = cyl_fivenum,
aes(x = factor(cyl), y = five, label = five),
nudge_x = .5)
如果有人正在處理大范圍並且必須log10轉換它們的y軸,我發現一些效果很好的代碼。 只需添加10^..y..
和scale_y_log10()
。 如果你沒有在..y..
之前添加10^
..y..
實際的分位數值將被對數轉換並如此顯示。
不行
ggplot(mtcars, aes(x=factor(cyl), y=mpg, fill=factor(cyl))) +
geom_boxplot(width=0.6) +
stat_summary(geom="text", fun.y=quantile,
aes(label=sprintf("%1.1f", ..y..), color=factor(cyl)),
position=position_nudge(x=0.45), size=3.5) +
scale_y_log10()+
theme_bw()
效果很好
ggplot(mtcars, aes(x=factor(cyl), y=mpg, fill=factor(cyl))) +
geom_boxplot(width=0.6) +
stat_summary(geom="text", fun.y=quantile,
aes(label=sprintf("%1.1f", 10^..y..), color=factor(cyl)),
position=position_nudge(x=0.45), size=3.5) +
scale_y_log10()+
theme_bw()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.