Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
762 views
in Technique[技术] by (71.8m points)

ggplot2 - R: How do I use coord_cartesian on facet_grid with free-ranging axis

Consider some facet_grid plot

mt <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) + geom_point() 
mt + facet_grid(vs ~ am, scales = "free") 

plottttt

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).

(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.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So, this is an old question, but I wanted to share a way that I found. The simplest seems to be to add artificial points to your data, e.g. at the lower left and top right of your data for each plot. Put this information into a separate data frame, then add it to the plot with geom_point using the parameter alpha=0 to make the points invisible. Set the scaling of the axis in facet_wrap to "free_x" or "free_y", depending on what you need.

Now ggplot scales every facet separately to accommodate the invisible points that you added. A bit hacky, but works nicely.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...