gpt4 book ai didi

r - 在 gtable 对象中设置宽度会折叠绘图;这曾经有效,但现在不再有效。

转载 作者:行者123 更新时间:2023-12-04 23:41:40 25 4
gpt4 key购买 nike

以下代码曾经有效但不再有效。有人知道发生了什么吗?它必须是底层 gtable 代码中的一些更改。

require(cowplot) # for plot_grid()
require(grid) # for unit_max()

# make two plots
plot.iris <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
geom_point() + facet_grid(. ~ Species) + stat_smooth(method = "lm") +
background_grid(major = 'y', minor = "none") +
panel_border()
plot.mpg <- ggplot(mpg, aes(x = cty, y = hwy, colour = factor(cyl))) +
geom_point(size=2.5)

g.iris <- ggplotGrob(plot.iris) # convert to gtable
g.mpg <- ggplotGrob(plot.mpg) # convert to gtable

iris.widths <- g.iris$widths[1:3] # extract the first three widths,
# corresponding to left margin, y lab, and y axis
mpg.widths <- g.mpg$widths[1:3] # same for mpg plot
max.widths <- unit.pmax(iris.widths, mpg.widths) # calculate maximum widths
g.iris$widths[1:3] <- max.widths # assign max. widths to iris gtable
g.mpg$widths[1:3] <- max.widths # assign max widths to mpg gtable

plot_grid(g.iris, g.mpg, labels = "AUTO", ncol = 1)

结果图如下:
enter image description here

它应该是这样的(y 轴线完全垂直对齐):
enter image description here

错误似乎发生在这一行:
g.iris$widths[1:3] <- max.widths

任何见解将不胜感激。

请注意,类似的解决方案已经使用了很长时间,参见例如 here.plot_grid() cowplot 中的函数也使用这样的代码来对齐绘图,它仍然有效。所以这让我完全迷惑了。

最佳答案

编辑
grid 3.3.0 版,这不再是问题。即包含 grid:::unit.list() 的代码行下面可以删除。

问题与单位的设置方式有关。看 g.iris$widths .您会注意到数字还在,但单位已被删除。看到这个 question and answer , 和 this one .将绘图转换为 gtables 后,您需要:g.iris$widths = grid:::unit.list(g.iris$widths)

require(grid) # for unit_max()
require(cowplot)

# make two plots
plot.iris <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
geom_point() + facet_grid(. ~ Species) + stat_smooth(method = "lm") +
background_grid(major = 'y', minor = "none") +
panel_border()
plot.mpg <- ggplot(mpg, aes(x = cty, y = hwy, colour = factor(cyl))) +
geom_point(size=2.5)

g.iris <- ggplotGrob(plot.iris) # convert to gtable
g.mpg <- ggplotGrob(plot.mpg) # convert to gtable

g.iris$widths = grid:::unit.list(g.iris$widths)
g.mpg$widths = grid:::unit.list(g.mpg$widths)

iris.widths <- g.iris$widths[1:3] # extract the first three widths,
# corresponding to left margin, y lab, and y axis
mpg.widths <- g.mpg$widths[1:3] # same for mpg plot

max.widths <- unit.pmax(iris.widths, mpg.widths) # calculate maximum widths

g.iris$widths[1:3] <- max.widths # assign max. widths to iris gtable
g.mpg$widths[1:3] <- max.widths # assign max widths to mpg gtable

plot_grid(g.iris, g.mpg, labels = "AUTO", ncol = 1)

关于r - 在 gtable 对象中设置宽度会折叠绘图;这曾经有效,但现在不再有效。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35822268/

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