在 annotate() 中插入自定义文本 - R 不工作

Inserting custom text in annotate() - R not working

已经有人问过了,但我找不到确切的答案。我想知道以下是否可行。

我在 ggplot2 库中有一堆散点图数据,每个都有不同的均值和标准差,以及观察次数。我想在每个不同的情节之上打印这些信息。因此,我正在计算并希望打印带有注释的那些。我正在做的事情如下:

m_axl5 <- as.character(round(mean(newdata$axl5), 5))
sd_axl5 <- as.character(round(sd(newdata$axl5), 5))
txt_m <- paste ("mean:", m_axl5)
txt_sd <- paste ("stdev:", m_axl5)
txt <-paste (txt_m, txt_sd, sep = '\n')
axl5 <- ggplot (newdata, aes(y=axl5, x= row.names(newdata))) + geom_point(position = position_jitter(w=0.1, h=0), colour= "red")+
    ggtitle("Axle 5 Weight - Match Error Difference") + xlab("") + ylab("Axle 5 Weight Match Error")
axl5 + theme(axis.ticks = element_blank(), axis.text.x = element_blank()) +annotate("text", x = 1, y = 10, label = txt)

每当我这样做时,都会出现以下错误:

Error: Incompatible lengths for set aesthetics: label

根据我的研究,我找不到以这种方式自定义标签或在 ggplot 上注释文本的方法。如果有人可以帮助我,或者至少可以指导我,如果这是早些时候完成的,我会非常高兴。

谢谢。

除了使用 annotate(),您还可以这样做

plot.title = 'Axle 5 Weight - Match Error Difference'
plot.subtitle = paste(txt_m, txt_sd, sep = '-')

ggtitle(bquote(atop(.(plot.title), atop(.(plot.subtitle), ""))))

参考:Add dynamic subtitle using ggplot