label_parsed of facet_grid in ggplot2 mixed with s

2019-05-22 13:54发布

问题:

I would like to plot a figure to custom the strip text with expressions and normal strings (included spaces), but got an error when the normal text contained spaces. This is an example to reproduce my question:

library(ggplot2)
labels <- c("'FT'[1]*' - Ctrl'", 
        "'FT'[tot]*' - FT'[1]*''",
        "'FT'[tot]*' - Ctrl'")
lbl_pd <- data.frame(impact = c('Direct impact', 'Direct impact', 
            'Indirect impact', 'Indirect impact'),
        type = c(labels[1], labels[2], labels[1], labels[2]),
        Latitude = -22.5, Longitude = 115,
        label = c('a', 'b', 'c', 'd'))
p <- ggplot(lbl_pd)
p <- p + geom_text(aes(Longitude, Latitude, label = label), size = 2)

p <- p + facet_grid(type~impact, labeller = label_parsed)
p

The error is

Error in parse(text = x) : <text>:1:8: unexpected symbol
1: Direct impact
       ^

There is no error if column "impact" without any spaces.

How could I solve this problem? Thanks for any suggestions.

回答1:

You can substitute your own label function:

library(plyr)

my_label_parsed <- function (variable, value) {
  if (variable == "impact") {
    return(as.character(value))
  } else {
    llply(as.character(value), function(x) parse(text = x))    
  }
}

library(ggplot2)

labels <- c("'FT'[1]*' - Ctrl'", 
        "'FT'[tot]*' - FT'[1]*''",
        "'FT'[tot]*' - Ctrl'")
lbl_pd <- data.frame(impact = c('Direct impact', 'Direct impact', 
            'Indirect impact', 'Indirect impact'),
        type = c(labels[1], labels[2], labels[1], labels[2]),
        Latitude = -22.5, Longitude = 115,
        label = c('a', 'b', 'c', 'd'))
p <- ggplot(lbl_pd)
p <- p + geom_text(aes(Longitude, Latitude, label = label), size = 2)

p <- p + facet_grid(type~impact, labeller = my_label_parsed)
p



回答2:

As of 2018, this is now possible to do directly with ggplot2:

p + facet_grid(type~impact, labeller = labeller(type = label_parsed))

Here's the link to the Tidyverse help page.



标签: r ggplot2