编辑刻面/条带和绘图之间的距离
Edit distance between the facet / strip and the plot
例如,
library(ggplot2)
ggplot(mpg, aes(displ, cty)) + geom_point() + facet_grid(cols = vars(drv))
我怎样才能改变地带和主要情节之间的距离? (例如,在地带和主情节之间创建一个间隙。)
但我不需要更改条带大小(与此不同)。
这个问题可以有多种解法。
geom_hline
一个 hacky 的方法是在图的顶部添加一行(可能是白色的,但这取决于您的主题)。我们可以使用 geom_hline
(或者 geom_vline
如果您的构面成行)来执行此操作。这会造成距离错觉。
library(ggplot2)
ggplot(mpg, aes(displ, cty)) +
geom_point() +
facet_grid(cols = vars(drv)) +
# Add white line on top (Inf) of the plot (ie, betweem plot and facet)
geom_hline(yintercept = Inf, color = "white", size = 4) +
labs(title = "geom_hline")
strip.background
另一种解决方案(如@atsyplenkov 所建议)是使用theme(strip.background = ...)
。在那里你可以指定边框的颜色。然而,这并不完美,因为它从所有方向切割边界(可能有一种方法可以改善这一点)。
ggplot(mpg, aes(displ, cty)) +
geom_point() +
facet_grid(cols = vars(drv)) +
# Increase size of the border
theme(strip.background = element_rect(color = "white", size = 3)) +
labs(title = "strip.background")
有一个更简单的解决方案
theme(strip.placement = "outside")
例如,
library(ggplot2)
ggplot(mpg, aes(displ, cty)) + geom_point() + facet_grid(cols = vars(drv))
但我不需要更改条带大小(与此不同
这个问题可以有多种解法。
geom_hline
一个 hacky 的方法是在图的顶部添加一行(可能是白色的,但这取决于您的主题)。我们可以使用 geom_hline
(或者 geom_vline
如果您的构面成行)来执行此操作。这会造成距离错觉。
library(ggplot2)
ggplot(mpg, aes(displ, cty)) +
geom_point() +
facet_grid(cols = vars(drv)) +
# Add white line on top (Inf) of the plot (ie, betweem plot and facet)
geom_hline(yintercept = Inf, color = "white", size = 4) +
labs(title = "geom_hline")
strip.background
另一种解决方案(如@atsyplenkov 所建议)是使用theme(strip.background = ...)
。在那里你可以指定边框的颜色。然而,这并不完美,因为它从所有方向切割边界(可能有一种方法可以改善这一点)。
ggplot(mpg, aes(displ, cty)) +
geom_point() +
facet_grid(cols = vars(drv)) +
# Increase size of the border
theme(strip.background = element_rect(color = "white", size = 3)) +
labs(title = "strip.background")
有一个更简单的解决方案
theme(strip.placement = "outside")