在ggplot2中标注boxplot [英] annotate boxplot in ggplot2
问题描述
p < - ggplot(mtcars,aes)我已经使用ggplot2创建了一个并排boxplot。 (x = factor(cyl),y = mpg))
p + geom_boxplot(aes(fill = factor(cyl)))
我想用最小值,最大值,第一四分位数,中位数和第三四分位数进行注释。我知道 geom_text()
可以这样做,可能 fivenum()
很有用。但我无法弄清楚我能做些什么!这些值应该显示在我的图中。
我能想到的最简洁的方法是使用 stat_summary
。我也将标签映射到颜色美学,但是,如果您愿意,您可以将标签设置为单色: c $ c> ggplot(mtcars,aes(x = factor(cyl),y = mpg,fill = factor(cyl)))+
geom_boxplot(width = 0.6)+
stat_summary(geom =文本,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结构)。
I've created a side-by-side boxplot using ggplot2.
p <- ggplot(mtcars, aes(x=factor(cyl), y=mpg))
p + geom_boxplot(aes(fill=factor(cyl)))
I want to annotate with min, max, 1st quartile, median and 3rd quartile in the plot. I know geom_text()
can do so and may be fivenum()
is useful. But I cannot figure out how exactly I can do!. These values should be displayed in my plot.
The most succinct way I can think of is to use stat_summary
. I've also mapped the labels to a color aesthetic, but you can, of course, set the labels to a single color if you wish:
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()
In the code above we use quantile
as the summary function to get the label values. ..y..
refers back to the output of the quantile
function (in general, ..*..
is a ggplot construction for using values calculated within ggplot).
这篇关于在ggplot2中标注boxplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!