0

I have the following very simple data set which I am representing with a multi-line line chart. The dataset:

foo <- c(105,205,301,489,516,678,755,877,956,1010)
foo1 <- c(100,201,311,419,517,690,710,880,970,1110)
foo2 <- c(105,209,399,499,599,699,799,899,999,1199)
bar <- c(110,120,130,140,150,160,170,180,190,200)

dataset <-data.frame(foo, foo1, foo2, bar)

So I am creating a multiline chart of this dataset using the following function in ggplot2:

ggplot(m,aes(bar)) + 
  geom_line(aes(y = foo,  colour = "foo"),linetype = 3) +
  geom_line(aes(y = foo1, colour = "foo1"), linetype = 5) +
  geom_line(aes(y = foo2, colour = "foo2"), linetype = 1)

And the chart that I get looks like this:

enter image description here

which is absolutely fine. Now I want to add another legend which should additionally say "solidline - foo2, dotted line - foo, dashed line - foo1". Basically the "linetype" which I added in the function. How could I possibly add the second legend in the graph? Thanks.

EDIT

I additionally tried

ggplot(m,aes(bar)) + 
  geom_line(aes(y = foo,  colour = "foo",linetype = 3)) +
  geom_line(aes(y = foo1, colour = "foo1", linetype = 5)) +
  geom_line(aes(y = foo2, colour = "foo2", linetype = 1))

but I get the error "Error: A continuous variable can not be mapped to linetype"

Abhiroop Sarkar
  • 2,251
  • 1
  • 26
  • 45

1 Answers1

2

Your data should be in tidy format first in order to make use of ggplot effectively:

library(ggplot2)
tidyr::gather(dataset, foo, value, -bar) %>% 
        ggplot(aes(bar, value, colour = foo, linetype = foo)) +
        geom_line()

enter image description here

mtoto
  • 23,919
  • 4
  • 58
  • 71
  • 1
    Thanks for this answer. It works perfectly except it requires me to additionally install the package "magrittr" to use the operator "%>%". Maybe the answer should mention that. Thanks again. – Abhiroop Sarkar Sep 07 '18 at 17:27
  • Is it possible to change the heading of the legend from "foo" to some custom heading? – Abhiroop Sarkar Sep 09 '18 at 00:22