标签机在使用facet_wrap时未能贴上标签并返回NA。

7

我正在尝试使用ggplot2中的标记函数来为分面图加上标签。当我运行代码时,没有任何错误或警告(虽然我知道这并不总是意味着一切都像我想象的那样工作),但是我的预定义标签没有应用到图形上,而只得到“NA”作为图形标签。我的数据的一个小子样如下:

w <- structure(list(Var1 = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 
2L), .Label = c("0", "1"), class = "factor"), Var2 = structure(c(1L, 
1L, 2L, 2L, 1L, 1L, 2L, 2L), .Label = c("0", "1"), class = "factor"), 
Freq = c(9L, 18L, 7L, 12L, 11L, 12L, 15L, 7L), Index = c(1L, 
1L, 1L, 1L, 2L, 2L, 2L, 2L), ComboCode = c("00", "10", "01", 
"11", "00", "10", "01", "11"), Var1Name = c("hibernate", 
"hibernate", "hibernate", "hibernate", "migrate", "migrate", 
"migrate", "migrate"), Var2Name = c("migrate", "migrate", 
"migrate", "migrate", "solitary_or_small_clusters", "solitary_or_small_clusters", 
"solitary_or_small_clusters", "solitary_or_small_clusters"
)), .Names = c("Var1", "Var2", "Freq", "Index", "ComboCode", 
"Var1Name", "Var2Name"), row.names = c("2.1", "2.2", "2.3", "2.4", 
"3.1", "3.2", "3.3", "3.4"), class = "data.frame")

panel_labels <- c("hibernate/migrate", "migrate/solitary_or_small_clusters")

这是我用来生成图表的代码:

library(ggplot2)
ggplot(w, aes(x = ComboCode, y = Freq, fill = ComboCode)) +
geom_bar(stat = "Identity") +
facet_wrap(~Index, labeller = labeller(Index = panel_labels)) +
guides(fill = FALSE)

如果有人能够解释为什么标签未被应用于绘图,我将不胜感激。
1个回答

16
< p >labeller 需要命名参数。

仅向 labeller 传递一个向量将返回 NA

library(ggplot2)

panel_labels <- c("hibernate/migrate", "migrate/solitary_or_small_clusters")
ggplot(w, aes(ComboCode, Freq, fill = ComboCode)) +
    geom_bar(stat = "Identity") +
    facet_wrap(~Index, labeller = labeller(Index = panel_labels)) +
    guides(fill = FALSE) +
    labs(title = "Vector")

传递命名向量将返回更改的标签:

panel_labels <- c("1" = "hibernate/migrate", "2" = "migrate/solitary_or_small_clusters")
ggplot(w, aes(ComboCode, Freq, fill = ComboCode)) +
    geom_bar(stat = "Identity") +
    facet_wrap(~Index, labeller = labeller(Index = panel_labels)) +
    guides(fill = FALSE) +
    labs(title = "Named vector")

输入图像描述


非常感谢@PoGibas!我尝试给你的答案点赞,但我还没有足够的声望积分。非常感谢。 - Curtis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接