Skip to content
Prev 275093 / 398506 Next

lattice::xyplot/ggplot2: plotting weighted data frames with lmline and smooth

Hi Michael:

Here's one way to get it from ggplot2. To avoid possible overplotting,
I jittered the points horizontally by +/- 0.2. I also reduced the point
size from the default 2 and increased the line thickness to 1.5 for
both fitted curves. In ggplot2, the term faceting is synonymous with
conditioning (by groups).

library('HistData')
library('ggplot2')
ggplot(PearsonLee, aes(x = parent, y = child)) +
   geom_point(size = 1.5, position = position_jitter(width = 0.2)) +
   geom_smooth(method = lm, aes(weights = PearsonLee$weight),
               colour = 'green', se = FALSE, size = 1.5) +
   geom_smooth(aes(weights = PearsonLee$weight),
               colour = 'red', se = FALSE, size = 1.5) +
   facet_grid(chl ~ par)

# If you prefer a legend, here's one take, pulling the legend inside
# to the upper left corner. This requires a bit more 'trickery', but
# the tricks are found in the ggplot2 book.

ggplot(PearsonLee, aes(x = parent, y = child)) +
   geom_point(size = 1.5, position = position_jitter(width = 0.2)) +
   geom_smooth(method = lm, aes(weights = PearsonLee$weight,
               colour = 'Linear'), se = FALSE, size = 1.5) +
   geom_smooth(aes(weights = PearsonLee$weight,
               colour = 'Loess'), se = FALSE, size = 1.5) +
   facet_grid(chl ~ par) +
   scale_colour_manual(breaks = c('Linear', 'Loess'),
                       values = c('green', 'red')) +
   opts(legend.position = c(0.14, 0.885),
        legend.background = theme_rect(fill = 'white'))


HTH,
Dennis
On Fri, Oct 21, 2011 at 8:22 AM, Michael Friendly <friendly at yorku.ca> wrote: