我使用了以下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帮助页面,但不知道如何操作。


当前回答

用变量,值作为参数的标签函数定义不适合我。另外,如果你想使用表达式,你需要使用lapply,而不能简单地使用arr[val],因为函数的参数是data.frame。

这段代码确实有效:

libary(latex2exp)
library(ggplot2)
arr <- list('virginica'=TeX("x_1"), "versicolor"=TeX("x_2"), "setosa"=TeX("x_3"))
mylabel <- function(val) { return(lapply(val, function(x) arr[x])) }
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) + geom_line() + facet_wrap(~Species, labeller=mylabel)

其他回答

注意,这个解决方案不会很好地工作,如果ggplot显示的因子比你的变量实际包含的少(如果你已经进行了子集设置,这可能会发生):

 library(ggplot2)
 labeli <- function(variable, value){
  names_li <- list("versicolor"="versi", "virginica"="virg")
  return(names_li[value])
 }

 dat <- subset(iris,Species!="setosa")
 ggplot(dat, aes(Petal.Length)) + stat_bin() + facet_grid(Species ~ ., labeller=labeli)

一个简单的解决方案(除了在names_li中添加所有未使用的因子,这可能很乏味)是使用droplevels()删除未使用的因子,要么在原始数据集中,要么在labbeler函数中,参见:

labeli2 <- function(variable, value){
  value <- droplevels(value)
  names_li <- list("versicolor"="versi", "virginica"="virg")
  return(names_li[value])
}

dat <- subset(iris,Species!="setosa")
ggplot(dat, aes(Petal.Length)) + stat_bin() + facet_grid(Species ~ ., labeller=labeli2)

从米沙巴利亚辛来的一条航线 :

facet_grid(。~vs, labeller = purrr::partial(label_both, sep = " #"))

看看它的实际应用

library(reprex)
library(tidyverse)

mtcars %>% 
  ggplot(aes(x="", y=gear,fill=factor(gear), group=am)) +
  geom_bar(stat="identity", width=1) +
  coord_polar("y", start=0) +
  facet_grid(.~vs, labeller = purrr::partial(label_both, sep = " #"))

由reprex包于2021-07-09创建(v2.0.0)

我认为所有其他解决方案都非常有用,但还有另一种方法。

我认为:

您已经安装了dplyr包,其中有方便的mutate命令 您的数据集名为survey。 调查% > % 突变(Hosp1 = Hospital1, Hosp2 = Hospital2,........)

此命令帮助您重命名列,但保留所有其他列。

然后执行同样的facet_wrap,现在就没问题了。

你试过改变医院载体的具体水平吗?

levels(survey$hospital)[levels(survey$hospital) == "Hospital #1"] <- "Hosp 1"
levels(survey$hospital)[levels(survey$hospital) == "Hospital #2"] <- "Hosp 2"
levels(survey$hospital)[levels(survey$hospital) == "Hospital #3"] <- "Hosp 3"

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

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())

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