1

I have a facet_wrap()-ed histogram pair that shows two histograms. One of the factor levels is a species binomial that should be in italics, but the other factor level should be in normal text:

library(tidyverse)
set.seed(1234)
data1 <- tibble(species = c(rep("H. sapiens",100), rep("Other Species",100)),
            height = c(rnorm(100,174,25),rnorm(100,125,15)))
plt <- ggplot(data1) +
  geom_histogram(aes(x=height,fill=species),bins=10) +
  facet_wrap(~species,nrow = 2)

facet_wrap histogram

I tried writing a labeller function:

lbl <- function(variable, value) {
  if(variable == "H. sapiens") value= italics("H. sapiens") else value
}

and using it in the call to facet_wrap:

facet_wrap(~species,nrow = 2, labeller = lbl)

but this replaced the previous facet label with the numerals 1 and 2, and produced a warning:

Warning: The labeller API has been updated. Labellers taking variableand value arguments are now deprecated. See labellers documentation.

How can I apply italics only to the strip in which H. sapiens appears, and only to the appropriate label in the legend? I realize these are two separate issues, but they both arise here.

I saw this post but it appears that there are unsolved issues (and it's a more-complicated example and quite confusing). Is there as solution?

Peter Pearman
  • 129
  • 1
  • 10

2 Answers2

1
library(grid)
g <- ggplotGrob(plt)
g$grobs[[13]]$grobs[[1]]$children[[2]]$children[[1]]$gp$font <- 3L
attr(g$grobs[[13]]$grobs[[1]]$children[[2]]$children[[1]]$gp$font,"names") <- "italic"
grid.draw(g)

enter image description here

Marco Sandri
  • 23,289
  • 7
  • 54
  • 58
1

You could do it with a separate 'labels' column in your data that is formatted as an expression, then use label_parse.

library(tidyverse)
library(stringr)
set.seed(1234)
data1 <- tibble(species = c(rep("H. sapiens",100), rep("Other Species",100)),
                height = c(rnorm(100,174,25),rnorm(100,125,15)))

data1$labels <- ifelse(data1$species == "H. sapiens",
                       str_replace(paste0("italic(", data1$species, ")"), " ", "~"),
                       str_replace(data1$species, " ", "~"))

plt <- ggplot(data1) +
  geom_histogram(aes(x=height,fill=species),bins=10) +
  facet_wrap(~labels,nrow = 2, labeller = label_parsed)
plt
jpshanno
  • 261
  • 2
  • 7