How to add mathematical symbols in ggplot facet_wrap text?

拜拜、爱过 提交于 2019-12-11 04:04:42

问题


This question explains how to add mathematical symbols inside a plot. But this doesn't work when the text is supposed to be stored in the data frame itself. This is the case for the text that appears in little boxes of the facet_wrap sub plots.

Here is a reproducible example. Let's say for example that I have this data in T and in m³ and that I would like to draw a plot like this one.

library(ggplot2)
dtf <- data.frame(year = rep(1961:2010,2),
                  consumption = cumsum(rnorm(100)),
                  item = rep(c("Tea bags","Coffee beans"),each=50),
                  unit = rep(c("T","m^3"),each=50))
ggplot(data=dtf)+
    geom_line(aes(x=year, y=consumption),size=1) +
    ylab(expression(paste("Consumption in T or ",m^3))) +
    scale_x_continuous(breaks = seq(1960,2010,10)) +
    theme_bw() + facet_wrap(item~unit, scales = "free_y")

ylab(expression(m^3)) displays the unit correctly. How could I display a similar m³ in the facet ?


回答1:


add labeller = label_parsed to your facet_wrap function, format your unit as m^3, and replace spaces in your labels with ~

library(ggplot2)
dtf <- data.frame(year = rep(1961:2010,2),
                  consumption = cumsum(rnorm(100)),
                  item = rep(c("Tea~bags","Coffee~beans"),each=50),
                  unit = rep(c("T","m^3"),each=50))
ggplot(data=dtf)+
  geom_line(aes(x=year, y=consumption),size=1) +
  ylab(expression(paste("Consumption in T or ",m^3))) +
  scale_x_continuous(breaks = seq(1960,2010,10)) +
  theme_bw() + facet_wrap(item~unit, scales = "free_y",labeller = label_parsed)



来源:https://stackoverflow.com/questions/37418211/how-to-add-mathematical-symbols-in-ggplot-facet-wrap-text

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