简体   繁体   English

R中的上标图例文本

[英]Superscript Legend Text in R

I am currently trying to superscript legend text in R similar to Latex.我目前正在尝试在类似于 Latex 的 R 中上标图例文本。 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.我有诸如"xx", "xxx", "yy", and "zz"变量,我想知道是否可以在 Latex 中将它们自动转换为上标,例如$x^2$ I know of expression(paste0("x"^"2")) for ggplot but it is unclear how to implement it or change the text automatically.我知道expression(paste0("x"^"2"))expression(paste0("x"^"2"))但不清楚如何实现它或自动更改文本。

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()

在此处输入图片说明 you still have to use expression()你仍然必须使用 expression()

EDIT: you can use rlang 's parse_exprs() with eval to autmatically convert you vars into expression:编辑:您可以使用 rlang 的 parse_exprs() 和 eval 自动将您的变量转换为表达式:



#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"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM