【发布时间】:2019-11-15 06:21:09
【问题描述】:
在 R 中,我使用 ggplot boxplot 绘制来自两个不同数据帧的数据,分别称为 ASD 和 TD。
每个数据框报告 3 个变量:
- 一个(数字)
- b(数字)
- 条件(分类,可以是“ASD”或“TD”)
我成功创建了两个图表;在每个图表中,我并排绘制了来自两个数据框的相同变量,分别为 a 和 b,以便对它们进行比较。然后我在每个图中添加了一个给定的字符串,即“Jonh”和“Jerry”。两个字符串都在 y=35 处打印,使用 annotate。
问题:如何更改每个字符串的 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):标签
感谢您的建议。
【问题讨论】:
-
myStr不在C.df_melted中,因此出现错误。此外,stackoverflow.com/questions/11889625/… 的可能重复项