gpt4 book ai didi

r - `ggplot2 - facet_grid` : Axes without ticks in interior facets

转载 作者:行者123 更新时间:2023-12-02 20:32:34 25 4
gpt4 key购买 nike

我想创建 facet_grid/facet_wrap 图,其中 x 轴在每个图表下重复,但刻度仅出现在最低图表上。

这是一个使用 facet_grid 绘制的 x 轴仅出现一次的示例

ggplot(mtcars, aes(y=mpg,x=cyl)) + 
facet_grid(am~., scales="free") +
geom_point() +
theme_classic() +
theme(strip.background = element_rect(colour="white", fill="white"),
strip.text.y = element_blank())

enter image description here

这是一个绘图示例,其中 x 轴出现两次,但两次都使用 facet_wrap

ggplot(mtcars, aes(y=mpg, x=cyl)) + 
facet_wrap(~am, ncol=1, scales="free") +
geom_point() +
theme_classic() +
theme(strip.background = element_rect(colour="white", fill="white"),
strip.text.x = element_blank())

enter image description here

我想要与上面的图相同的图,但上图的 x 轴上没有刻度线。或者,如果您愿意,我想要与第一个图相同的图,但在上图上有一个 x 轴。

最佳答案

这是一个非常冗长的解决方案,但我认为您无法仅使用常用的 ggplot 函数来获得所需的绘图。

library(ggplot2)
library(grid)

Plot <- ggplot(mtcars, aes(y=mpg, x=cyl)) +
facet_wrap(~am, ncol=1, scales="free") +
geom_point() +
theme_classic() +
theme(strip.background = element_rect(colour="white", fill="white"),
strip.text.x = element_blank())

关闭顶部 x 轴需要修改绘图的 gtable 对象。

Plot.build <- ggplot_gtable(ggplot_build(Plot))
axis.pos <- grep("axis-b-1-1", Plot.build$layout$name)
num.ticks <- length(Plot.build$grobs[[axis.pos]]$children[2]$axis$grobs[[1]]$y)

此步骤删除轴标签:

Plot.build$grobs[[axis.pos]]$children$axis$grobs[[2]]$children[[1]]$label <- rep("", num.ticks)

此步骤删除刻度线:

Plot.build$grobs[[axes.pos]]$children[2]$axis$grobs[[1]]$y <- rep(unit(0, units="cm"), num.ticks)

最后,使用以下方法生成绘图:

grid.draw(Plot.build)

enter image description here

关于r - `ggplot2 - facet_grid` : Axes without ticks in interior facets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48217290/

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