代码之家  ›  专栏  ›  技术社区  ›  Remi.b

ggplot2:使用y轴为每个刻面改变刻面宽度

  •  0
  • Remi.b  · 技术社区  · 7 年前

    虚拟数据

    d = data.frame(
        x = factor(LETTERS[c(1,2,3,4,1,2,3,4,1,2,1,2,1,2,1,2)]),
        y = c(100,80,70,60,130,90,65,60,2,3,3,3,2,2,1,2),
        grid = rep(letters[1:2], each=8)
    )
    

    问题

    ggplot(d, aes(x=x, y=y)) + facet_grid(~grid, scales="free",space="free_x") + geom_point()
    

    enter image description here

    我喜欢这个图表。我唯一的问题是两个网格使用相同的 Y 轴所以我试着用 facet_wrap 而不是 facet_grid 而且

    ggplot(d, aes(x=x, y=y)) + facet_wrap(~grid, scales="free") + geom_point()
    

    enter image description here

    但不幸的是, 小面包 没有“空格”参数,因此左右图形的宽度相同。

    问题

    如何才能使变量的级别之间的空间 d$x 在两个面之间相等(导致面具有不同的宽度),并且具有单独的 Y 每个面的轴。当然,我想保持平面水平对齐。

    0 回复  |  直到 7 年前
        1
  •  2
  •   Remi.b    7 年前

    使用ggplot grob并修改表中的宽度

    # Capture the plot
    q = ggplot(d, aes(x=x, y=y)) + facet_grid(~grid, scales="free",space="free_x") + geom_point()
    gt = ggplotGrob(q)
    
    # Modify the widths
    gt$widths[5] = unit(8, "cm")
    gt$widths[9] = unit(4, "cm")
    
    # Plot the graph
    grid.newpage()
    grid.draw(gt)
    

    enter image description here