gpt4 book ai didi

r - 用每条/组的观察数量注释 ggplot boxplot 方面

转载 作者:行者123 更新时间:2023-12-04 14:10:29 24 4
gpt4 key购买 nike

我已经查看了类似这些的其他问题 (Annotate ggplot2 facets with number of observations per facet),但没有找到对带分面的箱线图的单个条形图进行注释的答案。

这是我创建箱线图的示例代码:

require(ggplot2)
require(plyr)
mms <- data.frame(deliciousness = rnorm(100),
type=sample(as.factor(c("peanut", "regular")),
100, replace=TRUE),
color=sample(as.factor(c("red", "green", "yellow", "brown")),
100, replace=TRUE))

ggplot(mms, aes(x=type, y=deliciousness, fill=type)) +
geom_boxplot(notch=TRUE)+
facet_wrap(~ color,nrow=3, scales = "free")+
xlab("")+
scale_fill_manual(values = c("coral1", "lightcyan1", "olivedrab1"))+
theme(legend.position="none")

这里是相应的情节:

enter image description here

现在我想为颜色的每个方面单独注释每组(花生/常规)的观察次数,如我的绘图所示:

enter image description here

我已经做的是使用以下代码总结每种颜色和每组(花生/常规)的 dpyr 观察次数:

 mms.cor <- ddply(.data=mms, 
.(type,color),
summarize,
n=paste("n =", length(deliciousness)))

但是,我不知道如何将这个数据摘要添加到 ggplot 中。如何做到这一点?

最佳答案

使用 dplyrggplot2 尝试这种方法。您可以使用 mutate() 构建标签,然后根据 deliciousness 的最大值格式化为只有一个值。之后 geom_text() 可以根据需要启用文本。这里的代码:

library(dplyr)
library(ggplot2)
#Data
mms <- data.frame(deliciousness = rnorm(100),
type=sample(as.factor(c("peanut", "regular")),
100, replace=TRUE),
color=sample(as.factor(c("red", "green", "yellow", "brown")),
100, replace=TRUE))
#Plot
mms %>% group_by(color,type) %>% mutate(N=n()) %>%
mutate(N=ifelse(deliciousness==max(deliciousness,na.rm=T),paste0('n=',N),NA)) %>%
ggplot(aes(x=type, y=deliciousness, fill=type,label=N)) +
geom_boxplot(notch=TRUE)+
geom_text(fontface='bold')+
facet_wrap(~ color,nrow=3, scales = "free")+
xlab("")+
scale_fill_manual(values = c("coral1", "lightcyan1", "olivedrab1"))+
theme(legend.position="none")

输出:

enter image description here

关于r - 用每条/组的观察数量注释 ggplot boxplot 方面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64898257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com