r - ggplot:如何在不同的箱线图中注释不同位置的不同字符串
问题描述
在 R 中,我使用 ggplot boxplot绘制来自两个不同数据帧的数据,分别称为ASD和TD 。
每个数据框报告 3 个变量:
- 一个(数字)
- b(数字)
- 条件(分类,可以是“ASD”或“TD”)
我成功创建了两个图表;在每个图表中,我并排绘制了两个 datafames 中的相同变量,分别为a和b ,以便对它们进行比较。然后我在每个图中添加了一个给定的字符串,即“Jonh”和“Jerry”。两个字符串都使用annotate在 y=35 处打印。
问题:如何更改每个字符串的 y 位置?在示例中,我想在 y=10 处 打印字符串“Jerry”(在变量b的图中)
下面是我使用的代码:
#clearing variable and console
cat("\014")
rm(list = ls())
message("Graphic test for boxplot")
#libraries
library(ggplot2)
library(reshape2)
# creation of dataframe ASD, with numeric variables 'a' and 'b',
# and a categorial variable 'condition' with fixed value 'ASD'
a <- c(1:10)
b <- c(26:35)
ASD <- cbind(a,b)
ASD.df <-as.data.frame(ASD)
ASD.df$condition <- "ASD"
# creation of dataframe TD, with numeric variables 'a' and 'b',
# and a categorial variable 'condition' with fixed value 'TD'
a <- c(6:15)
b <- c(24:33)
TD <- cbind(a,b)
TD.df <-as.data.frame(TD)
TD.df$condition <- "TD"
# union of ASD and TD in a single dataframe C
C.df <- rbind(ASD.df,TD.df)
# reshaping of C for ggplot, using variable 'condition'
C.df_melted <- melt(C.df, id.var = "condition")
#strings I want to visualise on each graph
myStr <- c("John", "Jerry")
#do I want a fixed y lim?
FIXED_Y_LIM <- TRUE
myBox <- ggplot(data=C.df_melted, aes(x=condition, y=value, fill=variable))+
geom_boxplot(show.legend = FALSE) +
facet_wrap(~variable, scale="free") +
annotate(geom="text", x=1.5, y=35, label= myStr)
# it forces y scale in this range
if(FIXED_Y_LIM==TRUE)
{
myBox <- myBox + ylim(0, 40)
}
myBox
我试图解决修改注释行的问题
annotate(geom="text", x=1.5, y=35, label= myStr)
至
annotate(geom="text", x=1.5, y=c(35, 10), label= myStr)
但我得到这个我不明白的错误:
错误:美学必须是长度1或与数据相同(4):标签
感谢您的建议。
解决方案
使用ggplot2 中单个方面的注释文本,我们将位置和每个标签添加到C.df_melted
. 而不是annotate
我们使用geom_text
:
C.df_melted$x <- rep(1.5, nrow(C.df_melted))
C.df_melted$y <- c(rep(35, nrow(C.df_melted)/2), rep(10, nrow(C.df_melted)/2))
C.df_melted$myStr <- c(rep("John", nrow(C.df_melted)/2), rep("Jerry", nrow(C.df_melted)/2))
myBox <- ggplot(data=C.df_melted, aes(x=condition, y=value, fill=variable))+
geom_boxplot(show.legend = FALSE) +
facet_wrap(~variable, scale="free") +
geom_text(mapping = aes(x = x, y = y, label = myStr))
推荐阅读
- c# - 使用 c# 在网格中加载大数据
- c# - 以编程方式设置复选框样式模板标签 WPF
- webpack - Webpack 无法本地覆盖 Chrome 中的文件
- google-cloud-endpoints - 在 Cloud Endpoints 中使用具有多个 API 版本的 x-google-endpoints OpenAPI 扩展
- rest-assured - RestAssured:如果响应正文具有额外值,如何使用 JSON 模式验证响应正文?
- java - 如何修复“sun.security.validator.ValidatorException:PKIX 路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException”
- javascript - HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "Unauthorized" - 使用 Post 请求发送图像
- java - 如何从java中的csv文件中的特定字段中删除逗号
- php - 嵌套数组的 Laravel 类型转换
- ios - 离子电容器版本号