组合上标和包含 < 符号的变量标签时使用 ggplot geom_text

2024-06-09

我在将 R2 注释添加到多面图中时遇到问题,其中我的 R2 值有时

例如,使用 iris 数据集,我首先使用之前计算的 R2 值设置一个新的数据框。 x 和 y 位置也已设置,因为每个方面的 x 和 y 位置都不同(对于 iris 数据集来说不是必需的,但对于我的数据集来说是必需的)

SEr2s <- data.frame(Species = c("virginica",  "setosa",  "versicolor" ), 
                  xpos = c(5,7,7), ypos = c(4.2, 2, 4.2), 
                  lab = c("<0.01","0.08", "0.05"))

然后我运行我的情节:

XYPlot<-ggplot(data = iris, aes(x=Sepal.Length)) + 
  geom_point(aes(y = Sepal.Width), colour="grey40")+
  geom_smooth(aes(y = Sepal.Width), col="grey40", lwd=0.5, method="lm", se=FALSE) +
  geom_text(data = SEr2s, size=3, vjust=0, hjust=0,
            aes(x = xpos,  y = ypos, 
             label = paste("r^2==",lab)), parse = TRUE)+
  theme_bw() +
  theme(strip.background = element_blank(), strip.placement = "outside",
        panel.grid.minor = element_blank(), legend.position = "right") +
  facet_wrap(~Species)

我收到此错误:

解析错误(text = text[[i]]) : :1:7: 意外的“

有没有办法更改我的代码或标签数据框,以便它不会尝试评估这些符号?


如果您使用 ggtext 包,您可以避免使用plotmath,它可以处理基本的 HTML/markdown 作为输入。

library(ggplot2)
library(ggtext)

SEr2s <- data.frame(Species = c("virginica",  "setosa",  "versicolor" ), 
                    xpos = c(5,7,7), ypos = c(4.2, 2, 4.2), 
                    lab = c("<0.01","0.08", "0.05"))

ggplot(data = iris, aes(x=Sepal.Length)) + 
  geom_point(aes(y = Sepal.Width), colour="grey40")+
  geom_smooth(aes(y = Sepal.Width), col="grey40", lwd=0.5, method="lm", se=FALSE) +
  geom_richtext(
    data = SEr2s, size=3, vjust=0, hjust=0,
    aes(x = xpos,  y = ypos, label = paste0("r<sup>2</sup> = ", lab))
  ) +
  theme_bw() +
  theme(
    strip.background = element_blank(), strip.placement = "outside",
    panel.grid.minor = element_blank(), legend.position = "right") +
  facet_wrap(~Species)
#> `geom_smooth()` using formula 'y ~ x'

Created on 2019-12-02 by the reprex package https://reprex.tidyverse.org (v0.3.0)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

组合上标和包含 < 符号的变量标签时使用 ggplot geom_text 的相关文章

随机推荐