Plotting Expression in Legend

39 views
Skip to first unread message

Gokul Wimalanathan

unread,
Feb 12, 2018, 6:59:51 AM2/12/18
to ggplot2
I was trying to figure out how to evaluate expressions on ggplot2 legend labels. 

I could not evaluate the expressions which are labels of factors with any build in parameter or function, and I had to use a simple function to get it done in the end, and the code I used to evaluate the expressions are given below.

library("data.table")
library("ggplot2")

variable=rep(c("fscore","cm_sq","co2"),1)
value=rnorm(n = 3,1,1)
tmp_dt <- data.table(variable,value)
tmp_dt[,variable:=factor(variable,levels=c("fscore","cm_sq","co2"),labels = c("F[1]","cm^2","CO[2]"),ordered = T)]

parse_expr <- function(x){
    return(parse(text= x))
}

p <- ggplot(tmp_dt,aes(x=variable,y=value,fill=variable))
p <- p + geom_bar(stat="identity") + scale_fill_brewer(type="qual",palette = 1,labels=parse_expr)
p <- p + scale_x_discrete(labels=parse_expr)
p

I was wondering if there was a parameter in ggplot2 that already exists that would do this for me?

Thanks
Reply all
Reply to author
Forward
0 new messages