Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将文字放置在ggplot2中具有反转轴的绘图上_R_Ggplot2 - Fatal编程技术网

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
ie
geom\u text(label=paste(“italic(R^2)==”,R2),aes(x=10,y=30),parse=T)中放置x和y
请注意,通过使用带有固定
x
y
值的
geom_text
,您正在使
ggplot
在同一位置反复写入完全相同的文本,每行数据一次。这就是它看起来如此参差不齐的原因@user20650建议使用
注释
导致文本只编写一次。