svenkatesh
svenkatesh

Reputation: 1192

R stacked line graph with ggplot

I have a dataframe called m1, similar to the one below. I want to create a line graph of toSL.share by agebucket, with a separate line for each time.period. I am using ggplot, but I keep getting an error because agebucket isn't a continuous variable.

   agebucket time.period  toSL.share
1    (55,60]  X1968.2011 0.018442150
2    (60,65]  X1968.2011 0.020610489
3    (65,70]  X1968.2011 0.056670699
4    (70,75]  X1968.2011 0.065512286
5    (75,80]  X1968.2011 0.105771028
6    (80,85]  X1968.2011 0.134477048
7    (85,90]  X1968.2011 0.186838708
10   (55,60]  X1968.1984 0.000000000
11   (60,65]  X1968.1984 0.004602551
12   (65,70]  X1968.1984 0.003316970
13   (70,75]  X1968.1984 0.009582950
14   (75,80]  X1968.1984 0.024625690
15   (80,85]  X1968.1984 0.059762338
16   (85,90]  X1968.1984 0.139377908
19   (55,60]  X1985.1995 0.018040380
20   (60,65]  X1985.1995 0.009361666
21   (65,70]  X1985.1995 0.059075563
22   (70,75]  X1985.1995 0.059940681
23   (75,80]  X1985.1995 0.092601230 
24   (80,85]  X1985.1995 0.150035413
25   (85,90]  X1985.1995 0.153794013
28   (55,60]  X1996.2011 0.028367128
29   (60,65]  X1996.2011 0.038737821
30   (65,70]  X1996.2011 0.098084541
31   (70,75]  X1996.2011 0.111219309
32   (75,80]  X1996.2011 0.169499287
33   (80,85]  X1996.2011 0.164086942
34   (85,90]  X1996.2011 0.215390644

Here's my code to create the plot:

> m1$agebucket <- as.factor(m1$agebucket)
> ggplot(m1, aes(x=agebucket, y=toSL.share, col=time.period)) + geom_line()

And here's the error:

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

I don't understand the error. How can I create this graph with ggplot?

Upvotes: 1

Views: 1147

Answers (1)

Minnow
Minnow

Reputation: 1811

I'm partial to qplot so:

qplot(data=m1, agebucket, toSL.share, col=time.period, geom=c('point','line'), group=time.period)

Alternatively as ggplot:

ggplot(data=m1, aes(agebucket, toSL.share,group=time.period))+geom_line(aes(col=time.period))

See this link for more information.

Upvotes: 1

Related Questions