好吧,我被一个家庭酿造的ggplot难倒了.
我想要做的是有一个三行,一列刻面图,每个面都有不同的y轴标签.y轴的单位都是相同的.这将是最方便的,但谷歌搜索告诉我,这可能是不可能的.
或者,我使用grid.arrange 找到了这个解决方案,看起来它会起作用.但是,我想仅为一个绘图保留一个图例并将其从其他两个中移除,但保持间距就像它仍然存在一样,以便所有内容都很好.几年前有人遇到了同样的问题,但建议的解决方案已经过折旧,我无法理解如何使其在现代ggplot中运行.
任何帮助表示赞赏!使用facet是最简单的!
编辑后使用user20560的gridArrange解决方案添加绘图副本.非常接近那里,只想回到顶部和底部面板周围的盒子!

我假设(可能错误地)你想要添加单独的y轴标题而不是轴标签.[如果是你想要的标签不同,你可以使用scales参数facet_grid]
将有一个ggplot方法来做到这一点,但这里有几种方法可以自己调整grobs.
所以以mtcars数据集为例
library(ggplot2)
library(grid)
library(gridExtra)
Run Code Online (Sandbox Code Playgroud)
单程
p <- ggplot(mtcars, aes(mpg, wt, col=factor(vs))) + geom_point() +
facet_grid(gear ~ .)
# change the y axis labels manually
g <- ggplotGrob(p)
yax <- which(g$layout$name=="ylab")
# define y-axis labels
g[["grobs"]][[yax]]$label <- c("aa","bb", "cc")
# position of labels (ive just manually specified)
g[["grobs"]][[yax]]$y <- grid::unit(seq(0.15, 0.85, length=3),"npc")
grid::grid.draw(g)
Run Code Online (Sandbox Code Playgroud)
或使用 grid.arrange
# Create a plot for each level of grouping variable and y-axis label
p1 <- ggplot(mtcars[mtcars$gear==3, ], aes(mpg, wt, col=factor(vs))) +
geom_point() + labs(y="aa") + theme_bw()
p2 <- ggplot(mtcars[mtcars$gear==4, ], aes(mpg, wt, col=factor(vs))) +
geom_point() + labs(y="bb") + theme_bw()
p3 <- ggplot(mtcars[mtcars$gear==5, ], aes(mpg, wt, col=factor(vs))) +
geom_point() + labs(y="cc") + theme_bw()
# remove legends from two of the plots
g1 <- ggplotGrob(p1)
g1[["grobs"]][[which(g1$layout$name=="guide-box")]][["grobs"]] <- NULL
g3 <- ggplotGrob(p3)
g3[["grobs"]][[which(g3$layout$name=="guide-box")]][["grobs"]] <- NULL
gridExtra::grid.arrange(g1,p2,g3)
Run Code Online (Sandbox Code Playgroud)
如果它是你想要添加的轴标题,我应该问你为什么要一个不同的标题 - 小平面文本不能这样做吗?
| 归档时间: |
|
| 查看次数: |
4381 次 |
| 最近记录: |