tmalsburg
tmalsburg

Reputation: 346

ggplot2: Factor for x axis with geom_line doesn't work

I want a line plot, where value is plotted as a function of expt with one line per level in var:

Here is my data:

lines <- "
expt,var,value
1,none.p,0.183065327746799
2,none.p,0.254234138384241
3,none.p,0.376477571234912
1,male.p,-1.58289835719949
2,male.p,-1.98591548366901
3,male.p,-2.02814824729229
1,neutral.p,-2.01490302054226
2,neutral.p,-1.88178562088577
3,neutral.p,-1.68089687641625
1,female.p,-3.27294304613848
2,female.p,-3.07711187982237
3,female.p,-2.89652562347054
1,both.p,-2.40011011312792
2,both.p,-2.24495598015741
3,both.p,-2.78501124223834"
con <- textConnection(lines)
data <- read.csv(con)
close(con)

expt is a factor:

data$expt <- factor(data$expt)

Everything works as expected when I use geom_point

ggplot(data, aes(expt, value, colour=var)) + geom_point()

but when I use geom_line

ggplot(data, aes(expt, value, colour=var)) + geom_line()

I get the following error message

geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?

and an empty plot. When expt is numeric, it works but I prefer to use a factor because that gives me the correct labels on the x-axis. What's the problem here? I find it very counter-intuitive that this works with points but not with lines.

Upvotes: 7

Views: 9910

Answers (1)

beroe
beroe

Reputation: 12316

To plot a line graph with factors on the x-axis, you need to use group in addition to color...

ggplot(data, aes(expt, value, group=var, color=var)) + geom_line()

Gives me this output:

enter image description here

Upvotes: 18

Related Questions