Reputation: 505
I am currently trying to superscript legend text in R similar to Latex. I have variables such as "xx", "xxx", "yy", and "zz"
and am wondering if it is possible to automatically convert these to superscripts such as $x^2$
in Latex. I know of expression(paste0("x"^"2"))
for ggplot but it is unclear how to implement it or change the text automatically.
matrix <- matrix(rexp(200, rate=.1), ncol=20)
df <- data.frame(matrix)
variables <- c("x","y","z","xx","xy","yy","xz","yz","zz","xxx")
df$variables <- variables
new.df <- melt(df, id.vars="variables")
ggplot(new.df, aes(x = variable, y = value, col=variables, group = variables))+
geom_point()+
geom_line()
Upvotes: 4
Views: 1060
Reputation: 3022
you still have to use expression()
EDIT: you can use rlang ’s parse_exprs() with eval to autmatically convert you vars into expression:
#variables_ex <- rep(expression(paste(x^x[y])),10)
##EDIT: universal solution:
library(rlang)
variables <- c("x","y","z","xx","xy","yy","xz","yz","zz","xxx")
exlabel<-paste(variables,"^x[y]",sep="")
ggplot(new.df, aes(x = variable, y = value, col=variables, group = variables))+
geom_point()+
geom_line()+ labs(x = variables_ex)+
scale_color_discrete(name = "Superlegend", labels= eval(parse_exprs(exlabel)))+
theme( legend.text = element_text(color = "red"))
Upvotes: 4