Franziska Schreiber
Franziska Schreiber

Reputation: 1

How to combine 2 labeller functions in ggplot facet grid?

I want to create a facet grid of 2x2 with two different labellers needed.

a) Convert logic arguments into "before thrombin" or "after thrombin":

thrombin_names <- c(
  `FALSE` = "before thrombin", 
  `TRUE` = "after thrombin"
)
plot <- ggplot(data = current_data, 
  aes(x = which_timepoint, y = dIami, group = ID)
) +
  facefacet_grid(
    group ~ thrombin, 
    labeller = labeller(
      thrombin = as_labeller(thrombin_names))) +

b) Convert the given expressions into greek lettering:

group_labels <- c("alpha*beta*gamma", 
                 "alpha*beta['ins2X']*gamma")

current_data$group <- factor(current_data$group, 
  levels = c("wt", "2x"), 
  labels = group_labels
)

plot <- ggplot(
  data = current_data,
  aes(x = which_timepoint, y = dIami, group = ID)
) +
  facet_grid(
    group ~ thrombin,
    labeller = label_parsed
  ) +

Both labelling functions work perfectly fine on their own. However, I'm still looking for a solution to make them both work at the same time.

I tried to create a function that combines both labeller functions, so I can put one single labeller function into facet_grid:

combined_labeller <- function(data, params) {
  labeller1 <- labeller(thrombin = as_labeller(thrombin_names))
  labeller2 <- labeller()

  lapply(params, function(variable) {
    if (variable == "thrombin") {
      labeller1(data, params)
    } else {
      labeller2(data, params)
    }
  })
}

plot <- ggplot(
  data = current_data,
  aes(x = which_timepoint, y = dIami, group = ID)
) +
  facet_grid(
    group ~ thrombin,
    labeller = combined_labeller
  ) +
...

I got an

error in labeller(label_df) : argument "params" missing

Upvotes: 0

Views: 48

Answers (1)

stefan
stefan

Reputation: 123768

There is no need for as_labeller or a separate function. You can specify the labelling "function" to be applied to the rows or columns in one labeller() like so.

Using some fake example data:

library(ggplot2)

current_data <- expand.grid(
  thrombin = c(TRUE, FALSE),
  group = c("wt", "2x")
) |>
  transform(
    ID = 1,
    which_timepoint = 1,
    dIami = 1
  )

thrombin_names <- c("FALSE" = "before thrombin", "TRUE" = "after thrombin")
group_labels <- c("alphabetagamma", "alpha*beta['ins2X']*gamma")
names(group_labels) <- c("wt", "2x")
current_data$group <- factor(
  current_data$group,
  levels = c("wt", "2x"),
  labels = group_labels
)

ggplot(data = current_data, aes(x = which_timepoint, y = dIami, group = ID)) +
  geom_point() +
  facet_grid(group ~ thrombin,
    labeller = labeller(
      thrombin = thrombin_names,
      group = label_parsed
    )
  )

Upvotes: 1

Related Questions