Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 693
fstevens Avatar asked Nov 15 '13 16:11

fstevens


People also ask

How do I use superscript in ggplot2?

To add superscript as a title add bquote function with value inside ggtitle(). Parameter : like xlab and ylab functions, we can give the title for plot directly using this function. Here we will bquote() function for writing Superscript value ( Number VS Number2 ) as a title of plot.

How do you use superscript in R?

To indicate a subscript, use the underscore _ character. To indicate a superscript, use a single caret character ^ . Note: this can be confusing, because the R Markdown language delimits superscripts with two carets. In LaTeX equations, a single caret indicates the superscript.


1 Answers

It works with bquote:

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

enter image description here

like image 113
Sven Hohenstein Avatar answered Oct 06 '22 05:10

Sven Hohenstein