用plotmath保持尾随零 [英] Keeping trailing zeroes with plotmath

查看:143
本文介绍了用plotmath保持尾随零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 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 T)

有谁知道我能如何得到最后的0?我认为我可以像这样使用 paste()

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

但是我得到错误:

 错误解析(text = lab):< text>:1:11:意外数字常量
1:rho == - 0.5 0
^


解决方案

它是 plotmath 表达式解析问题;它不是 ggplot2 有关。



你可以做的是确保 0.50 被解释为一个字符串,而不是一个将被舍入的数值:

pre $ g $ pggplot(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 ,表达式(rho ==' - 0.50'))
text(0.8,0.8,expression(rho == 0.50))

如果您想要更通用的方法,请尝试如下所示:

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

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


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
             ^

解决方案

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.

这篇关于用plotmath保持尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆