首页 > 解决方案 > facet_wrap 带有垂直第二个标签和自由刻度

问题描述

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

注意:我不能使用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"))

标签: rfacet-wrap

解决方案


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


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)

绘图网格()


推荐阅读