首页 > 解决方案 > 来自存储在变量 R 中的文本的绘图标签中的上标

问题描述

我想打印 R 平方(上标)以及存储在变量中的其他一些文本。我的代码如下:

library(ggplot2)
library(extrafont)
loadfonts(device = "win")
dims = read.csv("example.csv")
write_graph <- function(x, y, colour)
{
  attach(dims)
  plot1 <- ggplot(dims, aes_string(x = x, y = y, fill = colour)) +
    geom_boxplot()+
    labs(color=colour) +
    scale_fill_grey(start = 0.3, end = 0.6) +
    theme_bw()+
    theme(legend.justification = c(1, 1), legend.position = c(1, 1)) +
    theme(axis.text.x = element_text(colour="black"), axis.text.y = element_text(colour="black"))+
    theme(text=element_text(family="Times New Roman"), panel.grid.major.y = element_blank(), panel.grid.minor.y = element_blank(), panel.grid.major.x = element_blank(), axis.title.x=element_blank(), axis.title.y=element_blank())+
    geom_label(aes(fill = NULL), show.legend = FALSE, x=x_cor, y=y_cor, label= model_text, family="Times New Roman", size=3)
  plot(plot1)
  detach(dims)
  return(plot1)
}
x_cor = 1.7; y_cor = -24; model_text = "Linear Model: Dim1 ~ Category*Region\nF(9, 972)=121.7; R^2 = 0.525; p < .001";
p <- write_graph("Category", "Dim1", "Region")
p

此链接上提供了示例数据。我了解本网站和互联网上有许多类似的问题。但是,我花了几个小时寻找解决问题的方法,但我无法理解如何将“R^2”(从model_text)中的 2 转换为上标。例如,我尝试了此答案中提供的解决方案,因为可以看出问题非常相似,但我无法实施建议的解决方案,主要是因为我的所有文本都存储在一个字符串中,我不知道如何将其分开以使解析函数可以理解表达式“R^2”。在这方面,我尝试了 , , , , 的几种paste组合expressionpaste0parse=TRUE没有as.expression成功as.character

标签: rggplot2

解决方案


最简单的方法是使用 Unicode 平方字符 R²。请参见Unicode 字符上标二

model_text = "Linear Model: Dim1 ~ Category*Region\nF(9, 972)=121.7; R² = 0.525; p < .001";

推荐阅读