【问题标题】:ggplot geom_text is messing up text order when using R mathematical notationggplot geom_text 在使用 R 数学符号时弄乱了文本顺序
【发布时间】:2022-01-31 18:57:36
【问题描述】:

我正在尝试使用geom_text 标记ggplot 中的点。我想使用 R 数学符号进行标记。例如,x 坐标 0.5 处的点应具有标签 1/2=0.5,其中 1/2 写为分数。我一直在尝试这段代码:

ggplot(data=NULL) +
  geom_point(aes(x=0.5, y=0)) +
  geom_text(aes(x=0.5, y=-0.1,
                label = paste("frac(1,2)"," = ", 1/2)), parse=TRUE) +
  xlim(-1,1) +
  ylim(-1, 1)

但是标签的顺序搞乱了,如下图所示:

我收到的是 =(1/2,0.5),而不是 1/2=0.5。在标签文本中使用frac() 时如何获得正确的顺序?

【问题讨论】:

    标签: r ggplot2 geom-text mathematical-typesetting


    【解决方案1】:

    label 放在aes 之外并使用双==,就像help("plotmath") 中所说的那样。

    ggplot(data=NULL) +
      geom_point(aes(x=0.5, y=0)) +
      geom_text(aes(x=0.5, y=-0.1),
                label = paste("frac(1, 2) == ", 1/2), parse=TRUE) +
      xlim(-1,1) +
      ylim(-1, 1)
    

    【讨论】:

    • 这个答案很容易适应我想用变量替换数字的情况。谢谢! a = 3; ggplot(data=NULL) + geom_point(aes(x=0.5, y=0)) + geom_text(aes(x=0.5, y=-0.1), label = paste("frac(",a,",2) ==", a/2), parse=TRUE) + xlim(-1,1) + ylim(-1, 1)
    【解决方案2】:

    您的label 应放在aes() 之外。

    ggplot(data=NULL) +
      geom_point(aes(x=0.5, y=0)) +
      geom_text(aes(x=0.5, y=-0.1),
                    label = expression(paste(frac(1,2), " = ", 0.5))) +
      xlim(-1,1) +
      ylim(-1, 1)
    

    【讨论】:

    • 非常感谢。是否有可能对此进行调整,使其也适用于变量。假设我将示例中的 1 替换为 a 并在前面初始化 a=3。有没有办法获得3/2=1.5 而不是a/2=a/2
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    相关资源
    最近更新 更多