我使用了以下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帮助页面,但不知道如何操作。
在不修改底层数据的情况下进行更改的最简单方法是:
使用as_labeller()创建一个对象。如果列名以数字开头,或者包含空格或特殊字符,不要忘记使用反标记:
# Necessary to put RH% into the facet labels
hum_names <- as_labeller(
c(`50` = "RH% 50", `60` = "RH% 60",`70` = "RH% 70",
`80` = "RH% 80",`90` = "RH% 90", `100` = "RH% 100"))
在ggplot中添加:
ggplot(dataframe, aes(x = Temperature.C, y = fit)) +
geom_line() +
facet_wrap(~Humidity.RH., nrow = 2, labeller = hum_names)
我觉得我应该加上我的答案,因为我花了很长时间才做到这一点:
这个答案是为你准备的:
您不想编辑原始数据
如果你需要表达式(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')
这个解决方案非常接近于@domi,但是它通过获取前4个字母和最后一个数字来缩短名称。
library(ggplot2)
# simulate some data
xy <- data.frame(hospital = rep(paste("Hospital #", 1:3, sep = ""), each = 30),
value = rnorm(90))
shortener <- function(string) {
abb <- substr(string, start = 1, stop = 4) # fetch only first 4 strings
num <- gsub("^.*(\\d{1})$", "\\1", string) # using regular expression, fetch last number
out <- paste(abb, num) # put everything together
out
}
ggplot(xy, aes(x = value)) +
theme_bw() +
geom_histogram() +
facet_grid(hospital ~ ., labeller = labeller(hospital = shortener))
在不修改底层数据的情况下进行更改的最简单方法是:
使用as_labeller()创建一个对象。如果列名以数字开头,或者包含空格或特殊字符,不要忘记使用反标记:
# Necessary to put RH% into the facet labels
hum_names <- as_labeller(
c(`50` = "RH% 50", `60` = "RH% 60",`70` = "RH% 70",
`80` = "RH% 80",`90` = "RH% 90", `100` = "RH% 100"))
在ggplot中添加:
ggplot(dataframe, aes(x = Temperature.C, y = fit)) +
geom_line() +
facet_wrap(~Humidity.RH., nrow = 2, labeller = hum_names)
下面是我如何使用2.2.1版本的ggplot2使用facet_grid(yfacet~xfacet):
facet_grid(
yfacet~xfacet,
labeller = labeller(
yfacet = c(`0` = "an y label", `1` = "another y label"),
xfacet = c(`10` = "an x label", `20` = "another x label")
)
)
请注意,这里不包含对as_labeller()的调用——这一点我曾纠结过一段时间。
这种方法的灵感来自帮助页面上的最后一个示例强制到标签器函数。