作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我已经查看了类似这些的其他问题 (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")
这里是相应的情节:
现在我想为颜色的每个方面单独注释每组(花生/常规)的观察次数,如我的绘图所示:
我已经做的是使用以下代码总结每种颜色和每组(花生/常规)的 dpyr 观察次数:
mms.cor <- ddply(.data=mms,
.(type,color),
summarize,
n=paste("n =", length(deliciousness)))
但是,我不知道如何将这个数据摘要添加到 ggplot 中。如何做到这一点?
最佳答案
使用 dplyr
和 ggplot2
尝试这种方法。您可以使用 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")
输出:
关于r - 用每条/组的观察数量注释 ggplot boxplot 方面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64898257/
我刚开始使用 Gnu Plot 并创建了一些简单的绘图。但是现在我遇到了一个新问题。 输入是这样的 csv 文件: name;n0;n1;n2 Benj;1;3;2 Silv;6;1;2 Steffi
我在 MongoDB 中有 2700 条记录。每个文档的大小约为 320KB。我使用的引擎是wiredTiger,集合的总大小约为885MB。 我的 MongoDB 配置如下: systemLog:
我是一名优秀的程序员,十分优秀!