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
509 views
in Technique[技术] by (71.8m points)

r - How do you set different scale limits for different facets?

Some sample data:

dfr <- data.frame(
  x = rep.int(1:10, 2),
  y = runif(20),
  g = factor(rep(letters[1:2], each = 10))
)

A simple scatterplot with two facets:

p <- ggplot(dfr, aes(x, y)) + 
  geom_point() +
  facet_wrap(~ g, scales = "free_y")

I can set the axis limits for all panels with

p + scale_y_continuous(limits = c(0.2, 0.8))

(or a wrapper for this like ylim)

but how do I set different axis limits for different facets?

The latticey way to do it would be to pass a list to this argument, e.g.,

p + scale_y_continuous(limits = list(c(0.2, 0.8), c(0, 0.5)))

Unfortunately that just throws an error in the ggplot2 case.

EDIT:

Here's a partial hack. If you want to extend the range of the scales then you can add columns to your dataset specifying the limits, then draw them with geom_blank.

Modified dataset:

dfr <- data.frame(
  x = rep.int(1:10, 2),
  y = runif(20),
  g = factor(rep(letters[1:2], each = 10)),
  ymin = rep(c(-0.6, 0.3), each = 10),
  ymax = rep(c(1.8, 0.5), each = 10)
)

Updated plot:

p + geom_blank(aes(y = ymin)) + geom_blank(aes(y = ymax))

Now the scales are different and the left hand one is correct. Unfortunately, the right hand scale doesn't contract since it needs to make room for the points.

In case it helps, we can now rephrase the question as "is it possible to draw points without the scales being recalculated and without explicitly calling scale_y_continuous?"

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I don't think this is possible yet in ggplot2. This discussion from January suggests the issue is under consideration.


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

...