How to use simultaneously superscript and variable in a axis label with ggplot2
Asked Answered
R

1

5

I would like to use together a variable (here the vector element "type") and a unit containing a superscript (here m^2) inside n axis label.

data <- list(houses = data.frame(surface = c(450, 320, 280),
                                 price = c(12, 14, 6)),
            flats = data.frame(surface = c(45, 89, 63),
                               price = c(4, 6, 9))) 

I achieve to display "m^2" using an expression,

for (type in c('houses', 'flats')){
  p <- ggplot(aes(x = surface, y = price), data = data[[type]]) +      
    geom_point() +
    xlab(expression(paste('surface of this type /', m^{2}))) 
}
p

but when I try to add the variable in the label, the following, of course, does not work :

for (type in c('houses', 'flats')){
  p <- ggplot(aes(x = surface, y = price), data = data[[type]]) +      
    geom_point() +
    xlab(expression(paste('surface of ', type, '/', m^{2})))
}
p

Would you have a suggestion ?

Rowland answered 15/11, 2013 at 16:0 Comment(0)
D
11

It works with bquote:

xlab(bquote('surface of' ~ .(type) ~ '/' ~ m^{2}))

enter image description here

Delafuente answered 15/11, 2013 at 16:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.