首页 > 解决方案 > ggplot:如何在不同的箱线图中注释不同位置的不同字符串

问题描述

在 R 中,我使用 ggplot boxplot绘制来自两个不同数据帧的数据,分别称为ASDTD 。

每个数据框报告 3 个变量:

在此处输入图像描述 在此处输入图像描述

我成功创建了两个图表;在每个图表中,我并排绘制了两个 datafames 中的相同变量,分别为ab ,以便对它们进行比较。然后我在每个图中添加了一个给定的字符串,即“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):标签

感谢您的建议。

标签: rggplot2

解决方案


使用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))

推荐阅读