r - 如何在 ggplot2 的 geom_text() 中解析 LaTeX 数学公式

标签 r ggplot2

我想在绘图中添加一个包含 Latex 公式的 geom_text(),以描述 2 个矩阵中每个值的平均百分比:

library(latex2exp)
library(ggplot2)
library(tidyverse)


percentage <- matrix(c(10,100,90,80,100,97,80,19,90,82,9,87),nrow=2)
colnames(percentage) <- c("value1","value2","value3","value4","value5","value6")
rownames(percentage) <- c("matrix1", "matrix2")
mean_p <- apply(percentage,2,mean)
mat <- c("matrix1", "matrix2")



percentage %>%
  as_data_frame() %>%
  gather(., Value , Percentage) %>%
  ggplot(., aes(x=Value,y=Percentage,color=rep(mat,ncol(percentage)))) +
  geom_bar(position = position_dodge(width = 0.8), stat = "identity", fill = "white")`

我尝试添加

lab <- character()
for(i in 1:ncol(percentage)){
lab <- c(lab,"",sprintf('$\\oslash%s$',mean_p[i]))
}
geom_text(aes(label=lapply(lab,TeX)),vjust=0,show.legend = FALSE,color="lightblue")

但这并不能正确转换 Latex 表达式。有人知道如何解决这个问题吗?

我想要生成的输出应该是这样的:

enter image description here

最佳答案

我提出了一个使用 annotate wherease geom_text 的解决方案,它主要受到以下解决方案的启发:

Annotate a plot made with ggplot2 with an equation using latex2exp::TeX

lab <- character()
for(i in 1:ncol(percentage)){
  lab <- c(lab, paste('$\\oslash$', mean_p[i], '$\\%$', sep = " "))
  }

percentage %>%
  as_data_frame() %>%
  gather(., Value , Percentage) %>%
  ggplot(., aes(x=Value,y=Percentage,color=rep(mat,ncol(percentage)))) +
  geom_bar(position = position_dodge(width = 0.8), stat = "identity", fill = "white") + 
 annotate('text',  x = 1:6, y = percentage[2,], label = lapply(lab, function(x){TeX(x, output = "character")}), hjust=0, size = 4, parse = TRUE)

关于r - 如何在 ggplot2 的 geom_text() 中解析 LaTeX 数学公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55937216/

相关文章:

r - 使用 data.table 在第一次匹配时进行高效的字符串分割

r - 密度曲线下的阴影(填充或颜色)面积(按分位数)

r - 如何计算有多少子字符串与列表中的至少一个元素匹配,前提是它们前面或后面没有否定?

r - ggplot2:具有自定义 y 限制的 geom_bar

r - 如何在 R 中的 ggplotly 中更改图例位置

r - ggplot2 饼图与 geom_text_repel

r - 将数据从嵌套数据框中提取到同一记录中

r - 使用 Rcpp 无法更快地获取 all()

r - ggplot2:如何在分组条形图上添加线条和 p 值?

r - ggplot barplot 根据两个类别的行的最大值进行排序