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

泄露秘密 提交于 2020-03-13 13:04:59

问题


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 ?


回答1:


It works with bquote:

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



来源:https://stackoverflow.com/questions/20005233/how-to-use-simultaneously-superscript-and-variable-in-a-axis-label-with-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!