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"

5
  • Move linetype inside aes just like what you did with color
    – Tung
    Commented Sep 7, 2018 at 17:14
  • @Tung tried that , I get the error "Error: A continuous variable can not be mapped to linetype" Commented Sep 7, 2018 at 17:16
  • 1
    What did you include? linetype = 'foo'?
    – Tung
    Commented Sep 7, 2018 at 17:18
  • 1
    Ideally you want to convert your data to long format similar to this
    – Tung
    Commented Sep 7, 2018 at 17:20
  • 1
    @Tung Ah! just saw your comment tried linetype = 'foo' and it works! Thanks Commented Sep 7, 2018 at 17:20

1 Answer 1

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

2
  • 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. Commented Sep 7, 2018 at 17:27
  • Is it possible to change the heading of the legend from "foo" to some custom heading? Commented Sep 9, 2018 at 0:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.