treetopdewdrop
treetopdewdrop

Reputation: 164

ggplot geom_smooth exclude negative values

I am trying to plot a linear regression with standard error (se) using ggplot2 geom_smooth which excludes negative values. Using scale_y_continuous unfortunately truncates part of the standard error fill. How can I get the se fill area to smoothly end at y=0?

See example (which uses y=10 rather than y=0, but same process):

ymax<-max(mtcars$mpg)
myplot<- ggplot(data=mtcars, aes(x=wt, y=mpg)) +  
geom_smooth(method=lm,   se=TRUE,fill = "#3399FF", colour="#0000FF",size =1)  +
geom_point(shape=20, size=2) +
scale_y_continuous(limits = c(10, ymax)) 
suppressMessages(print(myplot))  

I wish I could post the graph, but I have just joined stack overflow and don't have enough reputation points to post images. The graph shows the regression line ending at y=10 as expected, however the se fill ends as a vertical edge (not horizontal with the line below which se should be excluded). Thanks, and sorry I can't post the image :)

Upvotes: 4

Views: 5487

Answers (2)

thestral
thestral

Reputation: 551

With the new version of ggplot we now need:

 scale_y_continuous(limit=c(10,NA),oob=squish)

Upvotes: 5

Ben Bolker
Ben Bolker

Reputation: 226732

I think you want to load the scales package (library("scales")) and change your scale_y_continuous formulation to

 scale_y_continuous(limit=c(10,ymax),oob=squish)

Your other choice is

 + coord_cartesian(ylim = c(10, ymax)) 

Upvotes: 3

Related Questions