2

I have a dataset I'm plotting, with facets by variables (in the toy dataset - densities of 2 species). I need to use the actual variable names to do 2 things: 1) italicize species names, and 2) have the 2 in n/m2 properly superscripted (or ASCII-ed, whichever easier).

It's similar to this, but I can't seem to make it work for my case.

toy data

library(ggplot2)
df <- data.frame(x = 1:10, y = 1:10, 
 z = rep(c("Species1 density (n/m2)", "Species2 density (m/m2)"), each = 5),
 z1 = rep(c("Area1", "Area2", "Area3", "Area4", "Area5"), each = 2))

ggplot(df) + geom_point(aes(x = x, y = y)) + facet_grid(z1 ~ z)

I get an error (variable z not found) when I try to use the code in the answer naively. How do I get around having 2 variables in the facetting?

user2602640
  • 640
  • 6
  • 21
  • If you write out your labels with plotmath in your dataset, you can use the `labeller` argument with `label_parsed`. – aosmith Nov 28 '17 at 19:41
  • For example, you could change your variable to be `z = rep(c("italic(Species1)~density~(n/m^2)", "italic(Species2)~density~(m/m^2)"), each = 5)`. `label_parsed` works fine with two variables, as well. – aosmith Nov 28 '17 at 21:40

1 Answers1

2

A little modification gets the code from your link to work. I've changed the code to use data_frame to stop the character vector being converted to a factor, and taken the common information out of the codes so it can be added via the labeller (otherwise it would be a pain to make half the text italic)

library(tidyverse)
df <- data_frame(
        x = 1:10,
        y = 1:10, 
        z = rep(c("Species1", "Species2"), each = 5),
        z1 = rep(c("Area1", "Area2", "Area3", "Area4", "Area5"), each = 2)
      )

ggplot(df) + 
  geom_point(aes(x = x, y = y)) + 
  facet_grid(z1 ~ z, labeller = label_bquote(col = italic(.(z))~density~m^2))
Richard Telford
  • 9,558
  • 6
  • 38
  • 51