gpt4 book ai didi

r - 在 ggplot2 的 facet-grid/facet_wrap 中调整面板的相对空间

转载 作者:行者123 更新时间:2023-12-04 09:36:41 26 4
gpt4 key购买 nike

有没有办法改变 facet_grid 中各个面的 y 轴的高度/长度?或 facet_wrap ?

例如,

library(ggplot2)
ggplot(economics_long[economics_long$variable %in% c("pop", "uempmed"),], aes(date, value)) +
geom_line() +
facet_grid(variable~., scales = "free_y") +
theme(strip.background = element_blank())

enter image description here

在上图中,我希望 pop 时间序列 y 轴高度/长度是 uempmed y 轴长度 (2:1) 的两倍,而不管两个时间序列具有不同的 y轴刻度。

就像 Kohske 在这里所做的一样,在更旧版本的 ggplot2 中,它在 ggplot >=2.0.0 中不起作用:

https://kohske.wordpress.com/2010/12/25/adjusting-the-relative-space-of-a-facet-grid/

我知道我可以指定参数 space = "free"facet_grid ,但我认为该参数不能用于设置 2:1 的 y 轴比例?

我也不想使用“grid.arrange 类型”解决方案来排列单独创建的 ggplots(我可以在其中制作 2 个具有不同 y 轴长度的单独图),因为理想情况下我想利用 Shiny 的交互式ggplot2 单曲中的功能 facet_wrap绘图(例如,带有画笔的交互式 Shiny 刻面示例位于页面下方: http://shiny.rstudio.com/articles/selecting-rows-of-data.html)。

最佳答案

有多种选择。

facets , 你可以使用 facet_grid(..., space='free_y')将每行的高度调整为 y 刻度的长度。但是,在您的数据集中,底行最小化为一行(0-25 与 200,000 - 320,000)。

当 ggplot2 对象被绘制/打印时,它们首先被转换为 gtable对象。将您的绘图保存为 p ,我们可以调用ggplotGrob获取 gtable 对象。这是一种单向程序;转换后,您无法将 gtable 转换回 ggplot2 对象!

(g <- ggplotGrob(p))
TableGrob (12 x 8) "layout": 18 grobs
z cells name grob
1 0 ( 1-12, 1- 8) background rect[plot.background..rect.3766]
2 1 ( 6- 6, 4- 4) panel-1-1 gTree[panel-1.gTree.3696]
3 1 ( 8- 8, 4- 4) panel-1-2 gTree[panel-2.gTree.3711]
4 3 ( 5- 5, 4- 4) axis-t-1 zeroGrob[NULL]
5 3 ( 9- 9, 4- 4) axis-b-1 absoluteGrob[GRID.absoluteGrob.3725]
6 3 ( 6- 6, 3- 3) axis-l-1 absoluteGrob[GRID.absoluteGrob.3733]
7 3 ( 8- 8, 3- 3) axis-l-2 absoluteGrob[GRID.absoluteGrob.3741]
8 3 ( 6- 6, 6- 6) axis-r-1 zeroGrob[NULL]
9 3 ( 8- 8, 6- 6) axis-r-2 zeroGrob[NULL]
10 2 ( 6- 6, 5- 5) strip-r-1 gtable[strip]
11 2 ( 8- 8, 5- 5) strip-r-2 gtable[strip]
12 4 ( 4- 4, 4- 4) xlab-t zeroGrob[NULL]
13 5 (10-10, 4- 4) xlab-b titleGrob[axis.title.x..titleGrob.3714]
14 6 ( 6- 8, 2- 2) ylab-l titleGrob[axis.title.y..titleGrob.3717]
15 7 ( 6- 8, 7- 7) ylab-r zeroGrob[NULL]
16 8 ( 3- 3, 4- 4) subtitle zeroGrob[plot.subtitle..zeroGrob.3763]
17 9 ( 2- 2, 4- 4) title zeroGrob[plot.title..zeroGrob.3762]
18 10 (11-11, 4- 4) caption zeroGrob[plot.caption..zeroGrob.3764]

所有元素都设置在类似网格的布局中。布局中每一行的高度由 g$heights 给出:
> g$heights
[1] 5pt 0cm 0cm 0cm 0cm 1null 5pt 1null 0.396281911581569cm 1grobheight
[11] 0cm 5pt

将'panel-1-1'和'panel-1-2'的坐标匹配到这些高度,你会发现第6个和第8个元素都是 1null .您可以将它们更改为任何单位,cm、in、pt、... 1null只是在其他元素之后留下的,并在它们之间进行划分。所以我们可以把第6个高度改成 2null (注意使用双括号):
> g$heights[[6]] <- unit(2, 'null')
> grid.draw(g)

enter image description here

关于r - 在 ggplot2 的 facet-grid/facet_wrap 中调整面板的相对空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35735580/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com