ggplot2 - 使用 position = dodge 注释(标记)geom_boxplot [英] ggplot2 - annotate (labelling) geom_boxplot with position = dodge
本文介绍了ggplot2 - 使用 position = dodge 注释(标记)geom_boxplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在使用填充美学(或在 x 轴躲避样本)时,我无法在靠近箱线图的位置添加标签(在本例中为样本大小).
I'm not being able to add labels (sample size in this case) close to the boxplot when using fill aesthetics (or dodging the samples at x axis).
它适用于最常用的数据集(mtcars)和示例
it works fine for the most used dataset (mtcars) and example
library(ggplot2)
fun_length <- function(x){
return(data.frame(y=median(x),label= paste0("n=", length(x))))
}
ggplot(mtcars, aes(factor(cyl), mpg)) +
geom_boxplot() +
stat_summary(aes(x = factor(cyl)),
fun.data = fun_length, geom = "text",
vjust = +1, size = 4)
library(plyr)
ddply(mtcars, .(cyl), summarise, label = length(mpg))
cyl label
1 4 11
2 6 7
3 8 14
但我无法为这个版本添加相同的标签,现在显示每个 vs 级别的样本大小.
But I can't add the same labels for this version, now showing sample sizes for each vs level.
ggplot(mtcars, aes(factor(cyl), mpg)) +
geom_boxplot(aes(fill = factor(vs))) +
stat_summary(aes(x=factor(cyl)),
fun.data = fun_length, geom = "text")
ddply(mtcars, .(cyl, vs), summarise, label = length(mpg))
cyl vs label
1 4 0 1
2 4 1 10
3 6 0 3
4 6 1 4
5 8 0 14
欢迎任何帮助.提前致谢.
Any help will be welcome. Thanks in advance.
推荐答案
ggplot(mtcars, aes(factor(cyl), mpg)) +
geom_boxplot(aes(fill = factor(vs)), position=position_dodge(.9)) +
stat_summary(aes(x=factor(cyl), fill = factor(vs)), position=position_dodge(.9),
fun.data = fun_length, geom = "text",
vjust = +1, size = 4)
这篇关于ggplot2 - 使用 position = dodge 注释(标记)geom_boxplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文