贴标机不使用facet_wrap应用标签

时间:2018-06-06 10:42:25

标签: r ggplot2 facet-wrap

我试图在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 个答案:

答案 0 :(得分:3)

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

enter image description here