2013-03-13 46 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