这是@ClausWilke(see post)提供的一种解决方案的后续问题,该解决方案用于在主面板和边际图之间插入间隙。
如何确定(scale_x_continuous)限制?
另外,如果我们使用“ NA”作为上限会怎样?
# Example with limits set to: (-2,4.5)
require(ggplot2)
require(cowplot)
pmain <- ggplot(data = mpg, aes(x = cty, y = hwy)) +
geom_point() +
xlab("City driving (miles/gallon)") +
ylab("Highway driving (miles/gallon)") +
theme_grey()
xbox2 <- axis_canvas(pmain, axis = "x", coord_flip = TRUE) +
geom_boxplot(data = mpg, aes(y = cty, x = 1)) +
scale_x_continuous(limits = c(-2, 4.5)) + coord_flip()
ybox2 <- axis_canvas(pmain, axis = "y") +
geom_boxplot(data = mpg, aes(y = hwy, x = 1)) +
scale_x_continuous(limits = c(-2, 4.5))
p1 <- insert_xaxis_grob(pmain, xbox2, grid::unit(0.8, "in"), position = "top")
p2 <- insert_yaxis_grob(p1, ybox2, grid::unit(0.8, "in"), position = "right")
ggdraw(p2)
最佳答案
对于连续的X轴刻度,您可以使用expand_limits
在主图和边缘图之间添加一些空白。
例如,您的ybox2
是具有连续x轴比例的单箱图。默认情况下,该图的x范围大约为0.6到1.4(您可以通过运行ggplot(mpg, aes(y=hwy, x=1)) + geom_boxplot()
看到它)。以下代码改为将x轴下限设置为0.2,这意味着x轴范围的约0.4 /(0.8 + 0.4)= 33%将是主图和边际图之间的边距。我们对xbox2
做同样的事情。
ybox2 <- axis_canvas(pmain, axis = "y") +
geom_boxplot(data = mpg, aes(y = hwy, x = 1)) +
expand_limits(x = 0.2)
xbox2 <- axis_canvas(pmain, axis = "x", coord_flip = TRUE) +
geom_boxplot(data = mpg, aes(y = cty, x = 1)) +
coord_flip() +
expand_limits(x = 0.2)
p1 <- insert_xaxis_grob(pmain, xbox2, grid::unit(0.4, "in"), position = "top")
p2 <- insert_yaxis_grob(p1, ybox2, grid::unit(0.4, "in"), position = "right")
ggdraw(p2)