自然的方式ggplot2
要做这种事情需要在分类变量上进行刻面以创建子图。但是,如果您想将所有内容保留在同一个图表上,您可以尝试使用geom_tile()
分层是这样的:
df <-data.frame(x = factor(c(4,6,8)), colour = factor(c(1,2,1)))
ggplot(mtcars, aes(factor(cyl), mpg, fill=factor(am))) +
geom_boxplot() +
geom_tile(data=df, aes(x = x, y = 8, fill = colour))
![enter image description here](https://i.stack.imgur.com/dR5AV.png)
或者,正如您所建议的,您可以在其下方对齐一个附加图。你可以使用ggarrange()
in the ggpubr
为此的包:
plot1 <- ggplot(mtcars, aes(factor(cyl), mpg, fill=factor(am))) +
geom_boxplot() +
geom_tile(data=df, aes(x = x, y = 10, fill = colour))
theme(legend.position = 'none')
plot2 <- ggplot(df, aes(x=x, y=1, fill = colour)) +
geom_tile() +
theme_void() +
scale_fill_manual(values=c('orange', 'green', 'orange')) +
theme(legend.position = 'none')
library(ggpubr)
ggarrange(plot1, plot2, nrow = 2, heights = c(10, 1), align = 'h')
![enter image description here](https://i.stack.imgur.com/1g7vD.png)