Keeping trailing zeroes with plotmath

有些话、适合烂在心里 提交于 2020-01-02 02:01:46

问题


I'm using annotate() to overlay text on one of my ggplot2 plots. I'm using the option parse=T because I need to use the Greek letter rho. I'd like the text to say = -0.50, but the trailing zero gets clipped and I get -0.5 instead.

Here's an example:

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)

Does anyone know how I can get the last 0 to show up? I thought I could use paste() like this:

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

but then I get the error:

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

回答1:


It is an plotmath expression parsing problem; it's not ggplot2 related.

What you can do is ensure that 0.50 is interpreted as a character string, not a numeric value which will be rounded:

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

You would get the same behavior using base:

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

If you want a more general approach, try something like

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

There is an r-help thread related to this issue.



来源:https://stackoverflow.com/questions/15397789/keeping-trailing-zeroes-with-plotmath

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!