peter2108
peter2108

Reputation: 6130

How to set the data that geom_smooth smoothes

This works exactly as expected:

p = qplot(year, temp, data=CETW, geom=c("point", "smooth"))

The temperature is plotted against the year taking the data from the data frame CETW. The series is smoothed. Purely for aesthetic reasons I wanted to colour the warm temperatures, the normal temperatures, and the cold temperatures. There is an attribute CETW$classify whose values are "warm", "normal" and "cold". The following presents the data in the expected colours:

p = qplot(year, temp, data=CETW, colour=classify, geom=c("point", "smooth"))

but now the "smooth" thingy has decided to be clever and has applied separate smoothing curves to each of the three temperatures. This is silly because there are too few data points. So how do I tell smooth to smooth the whole series of temperatires as it did in the first case? It would be nice to see an answer that uses stat_smooth with method=loess.

As requested I am adding the data for CETW using dput:

structure(list(year = 1959:2011, temp = c(4.5, 5.08, 5.73, 3.43, 
1.25, 3.7, 3.8, 4.95, 5.6, 4.2, 3.2, 3.4, 4.55, 5.33, 5.2, 5.5, 
6.03, 5.13, 4.23, 4.75, 2.35, 4.63, 5.35, 3.45, 4.8, 4.35, 3.2, 
3.4, 3.68, 5.55, 6.75, 6.75, 4.25, 5.33, 5.2, 5.43, 5.83, 3.4, 
5.13, 6.55, 5.93, 5.95, 4.65, 5.93, 5.4, 5.48, 5.73, 4.33, 6.63, 
5.75, 4.4, 3.35, 4.03), classify = c("normal", "normal", "normal", 
"normal", "cold", "normal", "normal", "normal", "normal", "normal", 
"cold", "cold", "normal", "normal", "normal", "normal", "warm", 
"normal", "normal", "normal", "cold", "normal", "normal", "normal", 
"normal", "normal", "cold", "cold", "normal", "normal", "warm", 
"warm", "normal", "normal", "normal", "normal", "normal", "cold", 
"normal", "warm", "normal", "normal", "normal", "normal", "normal", 
"normal", "normal", "normal", "warm", "normal", "normal", "cold", 
"normal")), .Names = c("year", "temp", "classify"), row.names = c(NA, 
-53L), class = "data.frame")

Upvotes: 1

Views: 753

Answers (2)

Paul Lemmens
Paul Lemmens

Reputation: 635

Another way of accomplishing the suggestion of @Ramnath is to use the group parameter of aes().

ggplot(data=CETW, mapping=aes(x=year, y=temp, colour=classify)) +
+ geom_point() + geom_smooth(aes(group=1))

Upvotes: 0

Ramnath
Ramnath

Reputation: 55735

You should use ggplot, and specify options locally. Here is how it would work

p = ggplot(data = CETW, aes(x = year, y = temp)) +
    geom_point(aes(colour = classify)) +
    geom_smooth()

Here you specify the colour aesthetic only in the point layer and hence geom_smooth does not take that into account and gives you only a single line.

Let me know if this works

Upvotes: 2

Related Questions