如何在ggplot facet_wrap文本中添加数学符号? [英] How to add mathematical symbols in ggplot facet_wrap text?

查看:146
本文介绍了如何在ggplot facet_wrap文本中添加数学符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题解释了如何在绘图内添加数学符号.但这在应该将文本存储在数据框本身中时不起作用.在facet_wrap子图的小框中显示的文本就是这种情况.

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.

这是一个可复制的示例.例如,假设我在T和m³中都具有此数据,并且我想绘制一个像这样的图.

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))正确显示单位.如何在构面中显示类似的m³?

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

推荐答案

labeller = label_parsed添加到facet_wrap函数中,将单元格式设置为m^3,并用~

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)

这篇关于如何在ggplot facet_wrap文本中添加数学符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆