【问题标题】:ggplot annotate with greek symbol and (1) apostrophe or (2) in between textggplot 用希腊符号和(1)撇号或(2)在文本之间进行注释
【发布时间】:2014-12-04 20:05:00
【问题描述】:

无法在 ggplot annotate 中添加希腊字母,如果:它夹在其他文本之间,或者相关文本包含撇号。

例如,以下工作正常:

df <- data.frame(x =  rnorm(10), y = rnorm(10))
temp<-paste("rho == 0.34")
ggplot(df, aes(x = x, y = y)) + geom_point() +
    annotate("text", x = mean(df$x), y = mean(df$y), parse=T,label = temp)

但是,当我这样做时,ggplot 会爆炸:

df <- data.frame(x =  rnorm(10), y = rnorm(10))
temp<-paste("Spearman's rho == 0.34")
ggplot(df, aes(x = x, y = y)) + geom_point() +
    annotate("text", x = mean(df$x), y = mean(df$y), parse=T,label = temp)

ggplot 对这些特殊字符非常敏感。其他帖子似乎没有解决这个问题(如果没有,请道歉)。提前致谢。

【问题讨论】:

  • plot(1,1,t="n");text(1,1,expression("Spearman's"~rho == 0.34))

标签: r ggplot2 annotate


【解决方案1】:

我感受到了你的沮丧。除了使用@baptiste 评论的标签使用expression 之外,诀窍是将标签as.character 传递给ggplot

df <- data.frame(x =  rnorm(10), y = rnorm(10))
temp <- expression("Spearman's"~rho == 0.34)
ggplot(df, aes(x = x, y = y)) + 
  geom_point() + 
  annotate("text", x = mean(df$x), y = mean(df$y), 
           parse = T, label = as.character(temp))

【讨论】:

    【解决方案2】:

    如果有人试图将其用于事先不知道相关变量的动态场景,您还可以使用以下命令将表达式的转义版本创建为字符串:

    df <- data.frame(x =  rnorm(10), y = rnorm(10))
    
    spearmans_rho <- cor(df$x, df$y, method='spearman')
    plot_label <- sprintf("\"Spearman's\" ~ rho == %0.2f", spearmans_rho)
    
    ggplot(df, aes(x = x, y = y)) + 
      geom_point() + 
      annotate("text", x = mean(df$x), y = mean(df$y), parse = T, label=plot_label)
    

    【讨论】:

    • 人们可能还想保留尾随零,parse=TRUE 通常会丢弃这些零。这也可以通过解析数字来完成,即"\"Spearman's\" ~ rho == \"%0.2f\""
    猜你喜欢
    • 2018-07-17
    • 1970-01-01
    • 2015-02-25
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多