本文介绍了ggplot2中的facet_grid的label_parsed与空格和表达式混合在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想绘制一个图形来自定义带有表达式和普通字符串(包含空格)的条形文本,但是当正常文本包含空格时出现错误。这是重现我的问题的一个例子:

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.

推荐答案

您可以替换您自己的标签功能:

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

这篇关于ggplot2中的facet_grid的label_parsed与空格和表达式混合在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 09:01