I want to print R squared (in superscript) along with some other text which is stored in a variable. My code is as follows:
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
Example data is available at this link. I understand that there are a number of similar questions on this website and on the Internet. However I have spent several hours searching a solution to my problem and I have not been able to understand how to convert 2 in "R^2" (from model_text
) to superscript. As an example, I tried the solution provided in this answer, as it can be seen the problem is quite similar but I was unable to implement the solution suggested mainly because all of my text is stored in one single string, and I do not know how to separate it to make the expression "R^2" understandable for the parsing function. In this regard, I have tried several combinations of paste
, expression
, paste0
, parse=TRUE
, as.expression
, as.character
with no success.