ggplot中的序数上标注释R [英] Ordinal superscript in ggplot annotate R
问题描述
我希望能在将文本标签放置在ggplot图上(使用annotate
)时获得一些帮助,其中文本包含上标的序数后缀(或任何适当的后缀)和计算值.尽管阅读了关于SO和SE的一些问题,但我仍然无法使它正常工作.
I'm hoping I can get some help with placing a text label on a ggplot graph (using annotate
) where the text contains an ordinal suffix as superscript (or whatever the proper term is for that) and a computed value. Despite reading a few questions on SO and SE, I'm having trouble getting this to work.
这是一个最小的例子.
# my two attempts at creating the label
my.var = 10 / 3 # just a toy example
my.label.expr = paste(expression("20^th*"), " decile ", round(my.var, 4), sep = "")
my.label.bquote = bquote('Lift (' ~ 20^th* ~ "decile) : " ~ .
(round(my.var, 4), sep = ""))
test = data.frame(x = 1:10, y = 1:10)
ggplot(aes(x = x , y= y ), data = test) + geom_point() +
annotate("text", label = my.label.bquote,parse = TRUE, x = 5, y = 5,
colour = "red", size = 7)
使用label = my.label.expr
会给出错误:
# Error in parse(text = lab) : <text>:1:15: unexpected numeric constant
# 1: 20^th* decile 3.3333
使用label = my.label.bquote
会导致解释器提示输入?
Using label = my.label.bquote
causes interpreter to have prompt with a ?
我也尝试过使用parse = FALSE
,打印my.label.expr
,但是只显示文字,没有上标.使用parse = FALSE
作为bquote解决方案时,它根本不打印任何内容.
I also tried with parse = FALSE
, the my.label.expr
prints, but just displays the text literally, no superscript. With parse = FALSE
for the bquote solution, it prints nothing at all.
我觉得我对每个选项的语法都感到困惑.是否可以显示纯字母上标?任何帮助将不胜感激!
I feel like I've gotten confused between the syntax for each of these options. Is it possible to display a purely alphabetic superscript? Any help would be appreciated!
推荐答案
如何解决
my.label.expr = paste("20^{th}*' decile '*", round(my.var, 4))
ggplot(aes(x = x , y= y ), data = test) + geom_point() +
annotate("text", label = my.label.expr, parse=TRUE,
x = 5, y = 5, colour = "red", size = 7)
在这里,我们使用正确的?plotmath
语法(将指数分组在括号中)将值构建为字符串,然后设置parse=TRUE
以便对其进行评估.
Here we build the value as a character string with proper ?plotmath
syntax (grouping the exponent in brackets) and then setting parse=TRUE
so it is evaluated property.
这篇关于ggplot中的序数上标注释R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!