[R] Zooming in to a ggplot (a sort of ylim, but ylim won't do)

Frost Andy andy.frost2 at ntlworld.com
Tue Nov 30 10:34:59 CET 2010


Dear Helpers,

[Apologies, this is my second try, earlier message has been coded and eaten up'

I wonder whether you might be able to help me. I have a plot composed of
ggplot (and a follow on geom_smooth call). I would like to restrict the
display range of the y axis to a smaller range, a sort of zooming onto a
region. I attempted to use ylim, but it will effect the range (i.e. effect
the geom_smooth call). Is there any way that I can save the results up to
geom_smooth call and then restrict the print region. See the example code
below.

Any help is much appreciated.

With kind regards,

A.

# not very important
set.seed(1234)

# I am only trying to chop-off anything below zero (this for the example
only)
trunc_rnorm <- function(n, mean = 0, sd = 1, lb = 0)
{
    lb <- pnorm(lb, mean, sd)
    qnorm(runif(n, lb, 1), mean, sd)
}


# generate my data, this is not important
rsp<-trunc_rnorm(160,mean=c(
rep(20,10),rep(25,10),rep(40,10),rep(45,10),
rep(20,10),rep(27,10),rep(42,10),rep(45,10),
rep(20,10),rep(30,10),rep(44,10),rep(45,10),
rep(20,10),rep(30,10),rep(44,10),rep(45,10)),
  sd=c(rep(c(60,2,2,3),each=10,len=160)),
  lb=c(rep(c(0,0,0,0),each=10,len=160)))
d<-rep(c(rep(1,10),rep(2,10),rep(3,10),rep(4,10)),4)
v<-rep(c(rep(1,40),rep(2,40),rep(3,40),rep(4,40)),len=160)
rpl<-rep(1:10,len=160)
s<-rep(1:40,len=160)
df<-data.frame(s,d,rpl,v,rsp)
df<-transform(df,s=as.factor(s),v=as.factor(v),d=as.factor(d))


# important bits starts here

# This bit is good, but I only want to show the middle bits (the smooth,
splines for the four groups with their standard error regions
#
#windows() # uncomment this to see the plot on one window
g<-ggplot(df,aes(x=v,y=rsp,group=s,color=d))+geom_point()+geom_line(lty=2)
g1<-g+geom_smooth(aes(group=d,color=d))
print(g1)

# If I apply ylim (it does not do what I want)
# see the smooth splines are not what they appear in the first plot
#
# windows() # uncomment this to see the plot in a different window, so that
you can see that, the data are filtered by the ylim range
# that is not what I want, I wan't the plot above with high, low (y-axis,
chooped off)
g2<-g1+ylim(c(20,40))
print(g2)



More information about the R-help mailing list