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 ?
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.
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.
It works with bquote
:
xlab(bquote('surface of' ~ .(type) ~ '/' ~ m^{2}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With