2013-03-13 44 views
7

我正在使用annotate()叠加我的ggplot2图之一上的文字。我使用选项parse=T,因为我需要使用希腊字母rho。我希望文字说= -0.50,但尾部的零会被裁剪,而我会得到-0.5用绘图保留尾随零

下面是一个例子:

library(ggplot2) 
x<-rnorm(50) 
y<-rnorm(50) 
df<-data.frame(x,y) 

ggplot(data=df,aes(x=x,y=y))+ 
geom_point()+ 
annotate(geom="text",x=1,y=1,label="rho==-0.50",parse=T) 

有谁知道我怎样才能得到最后的0露面?我以为我可以用paste()这样的:

annotate(geom="text",x=1,y=1,label=paste("rho==-0.5","0",sep=""),parse=T) 

但后来我得到的错误:

Error in parse(text = lab) : <text>:1:11: unexpected numeric constant 
1: rho==-0.5 0 
      ^

回答

14

这是一个plotmath表达式分析问题;这不是ggplot2有关。

你能做的就是确保0.50被解释为一个字符串,而不是将四舍五入的数值。

ggplot(data=df, aes(x=x, y=y)) + 
    geom_point() + 
    annotate(geom="text", x=1, y=1, label="rho=='-0.50'", parse=T) 

你会使用base获得相同的行为:

plot(1, type ='n') 
text(1.2, 1.2, expression(rho=='-0.50')) 
text(0.8, 0.8, expression(rho==0.50)) 

如果您想要更通用的方法,请尝试类似于

sprintf('rho == "%1.2f"',0.5) 

有一个r-help thread与此问题有关。

+0

工作。谢谢! – 2013-03-14 15:03:18