我使用了以下ggplot命令:

ggplot(survey, aes(x = age)) + stat_bin(aes(n = nrow(h3), y = ..count.. / n), binwidth = 10)
  + scale_y_continuous(formatter = "percent", breaks = c(0, 0.1, 0.2))
  + facet_grid(hospital ~ .)
  + theme(panel.background = theme_blank())

生产

然而,我想将facet标签更改为更短的内容(如Hosp 1, Hosp 2…),因为它们现在太长了,看起来很局促(增加图形的高度不是一个选项,它将占用文档中的太多空间)。我查看了facet_grid帮助页面,但不知道如何操作。


当前回答

添加另一个类似于@domi的解决方案,解析数学符号、上标、下标、圆括号/方括号等。

library(tidyverse)
theme_set(theme_bw(base_size = 18))

### create separate name vectors
# run `demo(plotmath)` for more examples of mathematical annotation in R
am_names <- c(
  `0` = "delta^{15}*N-NO[3]^-{}",
  `1` = "sqrt(x,y)"
)

# use `scriptstyle` to reduce the size of the parentheses &
# `bgroup` to make adding `)` possible 
cyl_names <- c(
  `4` = 'scriptstyle(bgroup("", a, ")"))~T~-~5*"%"',
  `6` = 'scriptstyle(bgroup("", b, ")"))~T~+~10~degree*C',
  `8` = 'scriptstyle(bgroup("", c, ")"))~T~+~30*"%"'
)

ggplot(mtcars, aes(wt, mpg)) + 
  geom_jitter() +
  facet_grid(am ~ cyl,
             labeller = labeller(am  = as_labeller(am_names,  label_parsed),
                                 cyl = as_labeller(cyl_names, label_parsed))
             ) +
  geom_text(x = 4, y = 25, size = 4, nudge_y = 1,
            parse = TRUE, check_overlap = TRUE,
            label = as.character(expression(paste("Log"["10"], bgroup("(", frac("x", "y"), ")")))))

### OR create new variables then assign labels directly
# reverse facet orders just for fun
mtcars <- mtcars %>% 
  mutate(am2  = factor(am,  labels = am_names),
         cyl2 = factor(cyl, labels = rev(cyl_names), levels = rev(attr(cyl_names, "names")))
  )

ggplot(mtcars, aes(wt, mpg)) + 
  geom_jitter() +
  facet_grid(am2 ~ cyl2,
             labeller = label_parsed) +
  annotate("text", x = 4, y = 30, size = 5,
           parse = TRUE, 
           label = as.character(expression(paste("speed [", m * s^{-1}, "]"))))

由reprex包于2019-03-30创建(v0.2.1.9000)

其他回答

这对我很有用。

定义一个因素:

hospitals.factor<- factor( c("H0","H1","H2") )

在ggplot()中使用:

facet_grid( hospitals.factor[hospital] ~ . )

下面是另一个解决方案,它遵循@naught101给出的解决方案的精神,但更简单,也没有在ggplot2的最新版本上抛出警告。

基本上,首先创建一个命名字符向量

hospital_names <- c(
                    `Hospital#1` = "Some Hospital",
                    `Hospital#2` = "Another Hospital",
                    `Hospital#3` = "Hospital Number 3",
                    `Hospital#4` = "The Other Hospital"
                    )

然后将它用作标签器,只需修改@naught101给出的最后一行代码

... + facet_grid(hospital ~ ., labeller = as_labeller(hospital_names))

这里有一个避免编辑数据的解决方案:

假设你的图是由你的数据帧的组部分组成的,它有级别控制,test1, test2,然后创建一个由这些值命名的列表:

hospital_names <- list(
  'Hospital#1'="Some Hospital",
  'Hospital#2'="Another Hospital",
  'Hospital#3'="Hospital Number 3",
  'Hospital#4'="The Other Hospital"
)

然后创建一个'labeller'函数,并将其推到facet_grid调用中:

hospital_labeller <- function(variable,value){
  return(hospital_names[value])
}

ggplot(survey,aes(x=age)) + stat_bin(aes(n=nrow(h3),y=..count../n), binwidth=10)
 + facet_grid(hospital ~ ., labeller=hospital_labeller)
 ...

它使用数据帧的级别来索引hospital_names列表,并返回列表值(正确的名称)。


请注意,这仅适用于只有一个facet变量的情况。如果您有两个facet,那么您的labeller函数需要为每个facet返回不同的name向量。你可以这样做:

plot_labeller <- function(variable,value){
  if (variable=='facet1') {
    return(facet1_names[value])
  } else {
    return(facet2_names[value])
  }
}

其中facet1_names和facet2_names是由facet索引名('Hostpital#1'等)索引的名称的预定义列表。


编辑:如果你传递的变量/值的组合标签不知道,上述方法失败。你可以像这样为未知变量添加故障保险:

plot_labeller <- function(variable,value){
  if (variable=='facet1') {
    return(facet1_names[value])
  } else if (variable=='facet2') {
    return(facet2_names[value])
  } else {
    return(as.character(value))
  }
}

答自如何改条。ggplot中带有facet和margin=TRUE的文本标签


警告:如果您使用此方法对字符列进行facet,您可能会得到不正确的标签。请参阅此错误报告。在ggplot2的最新版本中修正。

我觉得我应该加上我的答案,因为我花了很长时间才做到这一点:

这个答案是为你准备的:

您不想编辑原始数据 如果你需要表达式(bquote)在标签和 如果您想要单独的标签名称-向量的灵活性

我基本上把标签放在一个命名向量中,这样标签就不会混淆或切换。标签器表达式可能更简单,但这至少是可行的(非常欢迎改进)。注意'(后引号)以保护facet-factor。

n <- 10
x <- seq(0, 300, length.out = n)

# I have my data in a "long" format
my_data <- data.frame(
  Type = as.factor(c(rep('dl/l', n), rep('alpha', n))),
  T = c(x, x),
  Value = c(x*0.1, sqrt(x))
)

# the label names as a named vector
type_names <- c(
  `nonsense` = "this is just here because it looks good",
  `dl/l` = Linear~Expansion~~Delta*L/L[Ref]~"="~"[%]", # bquote expression
  `alpha` = Linear~Expansion~Coefficient~~alpha~"="~"[1/K]"
  )


ggplot() + 
  geom_point(data = my_data, mapping = aes(T, Value)) + 
  facet_wrap(. ~ Type, scales="free_y", 
             labeller = label_bquote(.(as.expression(
               eval(parse(text = paste0('type_names', '$`', Type, '`')))
               )))) +
  labs(x="Temperature [K]", y="", colour = "") +
  theme(legend.position = 'none')

我有另一种方法可以在不改变底层数据的情况下实现相同的目标:

ggplot(transform(survey, survey = factor(survey,
        labels = c("Hosp 1", "Hosp 2", "Hosp 3", "Hosp 4"))), aes(x = age)) +
  stat_bin(aes(n = nrow(h3),y=..count../n), binwidth = 10) +
  scale_y_continuous(formatter = "percent", breaks = c(0, 0.1, 0.2)) +
  facet_grid(hospital ~ .) +
  opts(panel.background = theme_blank())

我上面所做的是改变原始数据帧中因子的标签,这是与原始代码相比的唯一不同之处。