R 将文字放置在ggplot2中具有反转轴的绘图上
我试图使用R 将文字放置在ggplot2中具有反转轴的绘图上,r,ggplot2,R,Ggplot2,我试图使用geom_text()在散点图上显示一些统计信息,但当我反转x轴时,文本消失 x = rnorm(20, mean = 10) y = rnorm(20, mean =30) R2 = cor(x, y)^2 R2 = signif(R2, 2) df = data.frame(x, y) # It works on a normal axis. library(ggplot2) ggplot(df, aes(x = x, y = y)) + geom_point(shape =
geom_text()
在散点图上显示一些统计信息,但当我反转x轴时,文本消失
x = rnorm(20, mean = 10)
y = rnorm(20, mean =30)
R2 = cor(x, y)^2
R2 = signif(R2, 2)
df = data.frame(x, y)
# It works on a normal axis.
library(ggplot2)
ggplot(df, aes(x = x, y = y)) + geom_point(shape = 1) +
geom_text(label=paste("italic(R^2)==",R2), x = 10, y = 30, parse = T) +
scale_x_continuous(limits = c(6, 14))
# But the text disappears when I reverse the x-axis:
ggplot(df, aes(x = x, y = y)) + geom_point(shape = 1) +
geom_text(label=paste("italic(R^2)==",R2), x = 10, y = 30, parse = T) +
scale_x_continuous(limits = c(14, 6), trans="reverse")
感谢您的建议。以下内容也将只编写一次文本,并将显示您提供的第一个示例中的值:
labels <- data.frame(xval = 10, yval = 30, labeltext = paste("italic(R^2)==",R2))
ggplot(df, aes(x = x, y = y)) +
geom_point(shape = 1) +
geom_text(data = labels, aes(x = xval, y = yval, label=labeltext), parse = T) +
scale_x_continuous(limits = c(14, 6), trans="reverse")
标签您可以使用annnotate
:p+annotate(geom=“text”,label=paste(“italic(R^2)==”,R2),x=10,y=30,parse=T)
其中p是您的绘图。或者在geom\u text
iegeom\u text(label=paste(“italic(R^2)==”,R2),aes(x=10,y=30),parse=T)中放置x和y
请注意,通过使用带有固定x
和y
值的geom_text
,您正在使ggplot
在同一位置反复写入完全相同的文本,每行数据一次。这就是它看起来如此参差不齐的原因@user20650建议使用注释
导致文本只编写一次。