Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 - set lower bound greater than lowest point

For some reason the function I'm fitting with ggplot2 is extending beyond the y-axis, even though the minimum value that can be obtained is zero. So, in attempting to restrict the lower bound to zero, I noticed that seemingly one cannot set only the lower bound such that data points are omitted (or predicted points, apparently). Is this true?

For instance, one can use expand_limits to zoom out, as it were:

require(ggplot2)
p = ggplot(mtcars, aes(wt, mpg)) + geom_point() 
p + expand_limits(y=0)

But one cannot zoom in:

p + expand_limits(y=15)

Same with setting the aesthetic:

p + aes(ymin=0)
p + aes(ymin=15)

I know I can use ylim, coord_cartesian, etc. to set both the upper and lower bound, but in this case, I'm passing a list to ggplot using lapply and the upper bound changes based on which object in the list is being plotted. So I'm back to plotting each object individually, which is very tedious. Any ideas?

EDIT: Hadley confirms this is not possible, so workaround by @Arun will have to do!

like image 499
jslefche Avatar asked Mar 05 '13 21:03

jslefche


1 Answers

It depends on how you want to plot the graphs, but if you can create a vector of the upper limit for each graph you could do something like this...

# Some vector of upper bounds for each plot which you can determine beforehand
ul <- c(20,25,30,35)
# Layout for printing plots (obviously you can handle this part however you like, this is just an example)
vplayout <- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y)

# Make some sensible number of rows/columns for plot page
x <- floor(sqrt(length(ul)))
y <- ceiling( length(ul) / x )

# Make list to hold plots
plots <- as.list( 1:length(ul) )
dim( plots ) <- c( x , y )


# Store plots with variable upper limit variable each time 
for( i in plots ){
        plots[[i]] <- ggplot(mtcars, aes(wt, mpg)) + geom_point()  + scale_y_continuous( limits = c( 15,ul[i]) , expand = c( 0 , 0 ) )
}


# Print the plots
grid.newpage()
pushViewport(viewport(layout = grid.layout(x, y)))
for( i in 1:x){
    for( j in 1:y){
        print( plots[[ i , j ]] , vp = vplayout( i , j ) )
        }
    }

enter image description here

like image 181
Simon O'Hanlon Avatar answered Sep 22 '22 02:09

Simon O'Hanlon