我想在绘图中添加一个包含 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 表达式。有人知道如何解决这个问题吗?
我想要生成的输出应该是这样的:
最佳答案
我提出了一个使用 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/