我使用了以下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帮助页面,但不知道如何操作。
如果你有两个面医院和房间,但只想重命名其中一个,你可以使用:
facet_grid( hospital ~ room, labeller = labeller(hospital = as_labeller(hospital_names)))
使用基于矢量的方法重命名两个面(如naught101的答案),你可以这样做:
facet_grid( hospital ~ room, labeller = labeller(hospital = as_labeller(hospital_names),
room = as_labeller(room_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()的调用——这一点我曾纠结过一段时间。
这种方法的灵感来自帮助页面上的最后一个示例强制到标签器函数。
我有另一种方法可以在不改变底层数据的情况下实现相同的目标:
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())
我上面所做的是改变原始数据帧中因子的标签,这是与原始代码相比的唯一不同之处。