【问题标题】:Keeping trailing zeroes with plotmath用 plotmath 保持尾随零
【发布时间】:2013-03-02 02:58:52
【问题描述】:

我正在使用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
             ^

【问题讨论】:

    标签: r ggplot2 plotmath


    【解决方案1】:

    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 与此问题相关。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      相关资源
      最近更新 更多