facet_wrap 带有垂直第二个标签和自由刻度

facet_wrap with vertical second labels and free scales

我正在使用 facet_wrap 显示 4 个图,每个国家 2 个。如何让国家名称垂直显示在左侧的 y 轴上? (即,我希望第一行用于加拿大,第二行用于 U.S 并删除第二行中地块的顶部标签)

注意:我不能使用 facet_grid,因为那不允许我使用自由秤。

ggplot( df ,aes(x=year, y = value,fill=scenario)) +
  geom_bar(stat = "identity",  position = "dodge",show.legend = TRUE) +
  facet_wrap(~ variable + country, ncol=2, scale="free") 

这是数据集:

   df <- structure(list(variable = structure(c(2L, 2L, 2L, 2L, 1L, 1L, 
1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L), .Label = c("Direct emissions costs", 
"Indirect costs", "Capital expenditure", "Revenue"), class = "factor"), 
    country = c("USA", "CAN", "USA", "CAN", "USA", "CAN", "USA", 
    "CAN", "USA", "CAN", "USA", "CAN", "USA", "CAN", "USA", "CAN"
    ), sector = c("LIVE", "LIVE", "LIVE", "LIVE", "LIVE", "LIVE", 
    "LIVE", "LIVE", "LIVE", "LIVE", "LIVE", "LIVE", "LIVE", "LIVE", 
    "LIVE", "LIVE"), year = c("2030", "2030", "2035", "2035", 
    "2030", "2030", "2035", "2035", "2030", "2030", "2035", "2035", 
    "2030", "2030", "2035", "2035"), scenario = structure(c(1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L
    ), .Label = c("2Ci", "2Cd"), class = "factor"), value = c(0.46, 
    1.79, 0.28, 0.68, 520.03, 137.17, 1099.74, 336.89, 0, 0, 
    -1, 0.08, 0, 0, 594.12, 262.43)), row.names = c(NA, -16L), groups = structure(list(
    variable = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), .Label = c("Direct emissions costs", 
    "Indirect costs", "Capital expenditure", "Revenue"), class = "factor"), 
    country = c("CAN", "CAN", "USA", "USA", "CAN", "CAN", "USA", 
    "USA"), year = c("2030", "2035", "2030", "2035", "2030", 
    "2035", "2030", "2035"), sector = c("LIVE", "LIVE", "LIVE", 
    "LIVE", "LIVE", "LIVE", "LIVE", "LIVE"), .rows = structure(list(
        c(6L, 14L), c(8L, 16L), c(5L, 13L), c(7L, 15L), c(2L, 
        10L), c(4L, 12L), c(1L, 9L), c(3L, 11L)), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), row.names = c(NA, -8L), class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))

您可以使用库中的 plot_grid() 函数 (cowplot)


canDf <- df %>% 
  filter(country == 'CAN')

p1 <- ggplot( canDf ,aes(x=year, y = value,fill=scenario)) +
  geom_bar(stat = "identity",  position = "dodge",show.legend = TRUE)+
  facet_wrap(~ variable, ncol=2, scale="free") +
  labs(title = canDf$country)

usDf <- df %>% 
  filter(country == 'USA')

p2 <- ggplot( usDf ,aes(x=year, y = value,fill=scenario)) +
  geom_bar(stat = "identity",  position = "dodge",show.legend = TRUE)+
  facet_wrap(~ variable, ncol=2, scale="free") +
  labs(title = usDf$country)

library(cowplot)
plot_grid(p1, p2, ncol = 1)