FAQ: geom_line() doesn’t draw lines


Probably one of the most frequently asked question is that geom_line() does not draw lines.
This is because x variable is factor.

# sample data
d <- data.frame(expand.grid(x=letters[1:4], g=factor(1:2)), y=rnorm(8))

# Figure 1a, 1b, and 1c.
ggplot(d, aes(x=x, y=y, colour=g)) + opts(title="Figure 1a") + geom_line() + geom_point()
ggplot(d, aes(x=x, y=y, colour=g, group=g)) + opts(title="Figure 1b") + geom_line() + geom_point()
ggplot(d, aes(x=x, y=y, colour=g, group=1)) + opts(title="Figure 1c") + geom_line() + geom_point()

The figure 1a does not draw any lines, while the figure 1b works well.
The key concept is “group” in aes.
The rule is simple:

  1. geom_line() tries to connect data points that belong to same group.
  2. different levels of factor variable belong to different group.

So, by specifying group=g in aes, the lines appear in Figure 1b.

Figure 1c would help to understand more.
In Figure 1c, all data points belong to group=1, hence all data points are connected.

8 thoughts on “FAQ: geom_line() doesn’t draw lines

  1. Pingback: R: ggplot2 – Each group consist of only one observation. Do you need to adjust the group aesthetic? at Mark Needham

  2. So, how would I create a legend for plot [1b] with a red for say “group1” and blue for “group2” (also stored in ‘d’)?

    Very helpful anyway.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s