R:如何在具有自由范围轴的 facet_grid 上使用 coord_cartesian [英] R: How do I use coord_cartesian on facet_grid with free-ranging axis
问题描述
考虑一些 facet_grid
图
mt <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) + geom_point()
mt + facet_grid(vs ~ am, scales = "free")
想象一下,我只想放大上图中的仅顶行,以仅显示 3 到 4 之间的 y 轴值.我可以使用 coord_cartesian()
如果它们不是多面的,或者如果我想放大所有图,但在这种情况下没有好的解决方案.我想我可以先对数据进行子集化,但这是有充分理由的禁忌(例如,会抛弃任何统计层等).
Imagine I just want to zoom on just the top row in the plots above to only show the y-axes values between 3 and 4. I could do this with coord_cartesian()
if they weren't faceted or if I wanted to zoom on all plots, but don't have a good solution in this case. I suppose I could subset the data first, but that is taboo for good reason (e.g. would throw off any statistical layer, etc).
(请注意,问题与此有关:R:{ggplot2}:如何/我可以独立调整 facet_grid 图上的 x 轴限制? 但那里的答案不适用于此目的.)
(Note that the question is related to this: R: {ggplot2}: How / Can I independently adjust the x-axis limits on a facet_grid plot? but the answer there will not work for this purpose.)
推荐答案
旧帖子,但我一直在寻找相同的东西,但找不到任何东西 - [也许这是一种在 y 轴上为两个因变量设置限制的方法使用 facet_grid()
Old post but i was looking for the same thing and couldn't really find anything - [perhaps this is a way Set limits on y axis for two dependent variables using facet_grid()
该解决方案不是很优雅/高效,但我认为它有效 - 基本上创建两个具有不同 coord_cartesian 调用的图并交换 grobs.
The solution is not very elegant/efficient but i think it works - basically create two plots with different coord_cartesian calls and swap over the grobs.
# library(ggplot2)
# library(gtable)
# Plot
mt <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) + geom_point()
# --------------------------------------------------------------------------------
p1 <- mt + facet_grid(vs ~ am, scales = "free") + coord_cartesian(ylim = c(1,6))
g1 <- ggplotGrob(p1)
p2 <- mt + facet_grid(vs ~ am, scales = "free") + coord_cartesian(ylim = c(3,5))
g2 <- ggplotGrob(p2)
# ----------------------------------------------------------
# Replace the upper panels and upper axis of p1 with that of p2
# Tweak panels of second plot - the upper panels
g1[["grobs"]][[6]] <- g2[["grobs"]][[6]]
g1[["grobs"]][[8]] <- g2[["grobs"]][[8]]
#Tweak axis
g1[["grobs"]][[4]] <- g2[["grobs"]][[4]]
grid.newpage()
grid.draw(g1)
这篇关于R:如何在具有自由范围轴的 facet_grid 上使用 coord_cartesian的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!