Search code examples
rggplot2expressionscalesymbols

How to properly use an expression in a scale function in ggplot2?


I am plotting some results with ggplot2. The data are organized in data frame structured like this:

   category  comparison    value
1  A         deltaXT/FT    6807
2  B         deltaXT/FT    11894
3  C         deltaXT/FT    1215
4  D         deltaXT/FT    42862
5  E         deltaXT/FT    34313
...

There are 4 comparisons in total, each subdivided into the categories A-E, in the same data frame (the plot looks like this). My aim is to substitute "deltaXT/FT" with "ΔXT/FT", using the greek symbol for Delta.

In the plot I'm using the "comparison" column to define the colour of the bars, like this:

ggplot(data=vars, aes(x=category, y=value, fill=comparison)) + 
...
scale_fill_manual(values=c("deltaXT/FT"="#6FA9BC"), ...)

Basically, everything works just fine while I use "deltaXT/FT" in scale_fill_manual and in the original data frame. If I try to use expression(Delta * "XT/FT")="#6FA9BC", ...) I get this error:

Error: unexpected '=' in:
...
scale_fill_manual(values=c(expression(Delta * "XT/FT"))="

The issue seems to be with scale_fill_manual(): the expression() couldn't be used as key in there. I read other threads here in StackOverflow where people got suggested to use bquote(expression()=value) but the error didn't change when using it.

Any suggestion on how to get past this problem and have a nice ΔXT/FT name in the legend?

EDIT: copy-pasting the Δ character into the Rscript where needed works, but I'm more interested in if the expression() can be used as a key in such situation in general.


Solution

  • You can just change the label associated with each comparison, not the value that's mapping it.

    ... +
    scale_color_manual(values = c("deltaXT/FT" = "#6FA9BC"), 
                       labels = c("deltaXT/FT" = expression(Delta * "XT/FT")))
    

    Or, in a complete plot:

    library(ggplot2)
    ggplot(data=df, aes(x=category, y=value, color=comparison)) + 
      geom_point(size = 5) +
      scale_color_manual(values=c("deltaXT/FT"="#6FA9BC"), 
                         labels = expression(Delta * "XT/FT"))
    

    Data:

    df <- read.table(text = ' category  comparison    value
    1  A         deltaXT/FT    6807
                     2  B         deltaXT/FT    11894
                     3  C         deltaXT/FT    1215
                     4  D         deltaXT/FT    42862
                     5  E         deltaXT/FT    34313', header = TRUE)