how: simple piecewise geom_smooth?

325 views
Skip to first unread message

dhaval

unread,
Nov 28, 2012, 1:55:40 AM11/28/12
to ggp...@googlegroups.com
Hi,

I am trying to create a piecewise geom_smooth, that is, I am trying to create difference geom_smooth curve for different portions for my x-axis.

Using the following code:

y = floor(runif(100,1,10))
df = as.data.frame(cbind(x,y))
rm(p)
p <- ggplot(df,aes(x,y))
p <- p + geom_line(aes(group = 1))
p <- p + geom_smooth(aes(df$x,df$y,group = 1, data = subset(df, x>90), fullrange = FALSE))
p

I want to create a geom_smooth curve only for the portion that is for x > 90 (ideally, i would like one for each of x<30, one for 31<x<50, etc). 

I have tried various combinations, but I don't seem to know what is wrong as it does not work. I still want to have a geom_line for the whole x-series, but want different geom_smooths overlayed.

I get errors such as "Error: Aesthetics must either be length one, or the same length as the dataProblems:subset(df, x > 90)", "ggplot2 doesn't know how to deal with data of class uneval", "arguments imply differing number of rows" for different orderings of arguments.

Help would be greatly appreciated,

Thank you,

Dhaval

Dennis Murphy

unread,
Nov 28, 2012, 4:52:05 AM11/28/12
to dhaval, ggp...@googlegroups.com
Hi:

Here's a toy example to illustrate:

DF <- data.frame(x = x, y = intercpt + slope*x + rnorm(100, s = 2),
region = cut(x, c(0, 30, 60, 100)))
ggplot(DF, aes(x = x, y = y, color = region)) +
geom_point() + geom_smooth(method = lm, size = 1)

If you'd like different labels for the legend key items, look into the
labels argument of cut().

Dennis
> --
> You received this message because you are subscribed to the ggplot2 mailing
> list.
> Please provide a reproducible example:
> https://github.com/hadley/devtools/wiki/Reproducibility
>
> To post: email ggp...@googlegroups.com
> To unsubscribe: email ggplot2+u...@googlegroups.com
> More options: http://groups.google.com/group/ggplot2

Dhaval Adjodah

unread,
Nov 28, 2012, 8:42:14 PM11/28/12
to Dennis Murphy, ggp...@googlegroups.com
Hi Dennis,

That worked, thanks a lot!

It helped knowing how to cut date objects too, using:

DF = data.frame(other_DF, cut.Date(date, 
                                  c(as.Date("2010-11-05", format="%Y-%m-%d"),
                                    as.Date("2010-11-28", format="%Y-%m-%d"),
                                    as.Date("2010-12-16", format="%Y-%m-%d"),
                                    as.Date("2010-12-26", format="%Y-%m-%d"), 
                                    as.Date("2011-01-131", format="%Y-%m-%d")),
                                  right = TRUE,
                                  labels = c("1", "2", "3", "4")))

Thank you wonderful ggplot2 community,

Dhaval
Reply all
Reply to author
Forward
0 new messages