Creating curves for each factor level

Let's see how to produce multiple curves in ggplot. We use the Children dataset (refer to the Creating multiple curves simultaneously section in Chapter 3, Mastering the qplot Function) to produce a line graph of height against age for each child. We created this particular graph in qplot and now we create it in ggplot, but we amend it a little. You can cut and paste the data directly from the code file for this chapter. Remember that the data for each child is arranged in a single column that holds six measurements of height for each child. We will include large points (size = 3) and slightly heavier lines (lwd = 1.2) using geom_point() and geom_line(), respectively. We will also map a color to the variable Child, so that both points and lines have a unique color for each child.

Finally, we impose our own color scheme using scale_color_manual():

ggplot(cheight, aes(x=Age, y=Height, color = factor(Child))) + geom_point(size = 3) +  geom_line(lwd = 0.7) + labs(title = "Childrens' Growth Patterns") + labs(x = "Age (years)", y = "HEIGHT (cm)") + scale_color_manual(values = c("red", "yellow", "blue", "darkgreen"))

Now we get this graph:

Creating curves for each factor level

The arrangement of the data within a single column made it easy to create a graph with all four curves at once.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset