用R中的乳胶注释ggplot2面标签

时间:2019-06-09 22:43:21

标签: r ggplot2 latex

给出示例数据集:

size = 10000
dist = seq(0, 10, length.out=size)
cohort.kv = list(A=3,B=40,C=44)
cohort = sample(names(cohort.kv), size, TRUE)
cohort.v = mapply(function(v) cohort.kv[[v]], cohort)
across.kv = list(ONE=1,TWO=2,THREE=3)
across = sample(names(across.kv), size, TRUE)
across.v = mapply(function(v) across.kv[[v]], across)
along.kv = list(FIVE=5, EIGHT=8, ELEVEN=11)
along = sample(names(along.kv), size, TRUE)
along.v = mapply(function(v) along.kv[[v]], along)
df = data.frame(
  dist=dist, cohort=cohort, across=across, along=along,
  value=sin(dist/across.v+cohort.v)*along.v
)
df$across = factor(df$across, levels=names(across.kv))
df$along = factor(df$along, levels=names(along.kv))

我正在尝试将胶乳添加到构面标签中。 This answer说明了如何将乳胶添加到ggplot标签。下面的代码生成了一个多面ggplot,在轴标签中带有乳胶,并修改了多面标签。

library(ggplot2)
# install.packages("latex2exp", dependencies=TRUE)
library(latex2exp)
(
  ggplot(df, aes(x=dist, y=value, color=cohort))
  + geom_line()
  + facet_grid(
    rows=vars(across),
    cols=vars(along),
    labeller=labeller(
      across=c(ONE="UNO",TWO="DOS",THREE="TRES"),
      along=c(FIVE=TeX("$V_5$"),EIGHT=TeX("$V_8$"),ELEVEN=TeX("$V_11$"))
    )
  )
  + xlab(TeX("Distance ($\\delta$)"))
  + ylab(TeX("Intensity ($\\alpha$)"))
)

Plot result

along=c(FIVE=TeX("$V_5$"),EIGHT=TeX("$V_8$"),ELEVEN=TeX("$V_11$"))行应更改顶部的顶部构面标签,但不能更改。

如何在面部标签上添加乳胶?

1 个答案:

答案 0 :(得分:2)

我确信有更好的方法可以做到这一点,但是一种方法是更改​​级别:

levels(df$across) <- c(ONE="UNO", TWO="DOS", THREE="TRES")
levels(df$along) <- c(FIVE = TeX("$V_5$"), EIGHT = TeX("$V_8$"), ELEVEN = TeX("$V_{11}$"))

然后将label_parsed用于贴标机:

ggplot(df, aes(x=dist, y=value, color=cohort)) +
 geom_line() +
 facet_grid(
  rows=vars(across),
  cols=vars(along),
  labeller=label_parsed
) +
  xlab(TeX("Distance ($\\delta$)")) +
  ylab(TeX("Intensity ($\\alpha$)"))

label_parsed将标签解释为绘图表达式。