Adding a second legend to line chart in ggplot2 in R [duplicate]

匿名 (未验证) 提交于 2019-12-03 01:42:02

问题:

This question already has an answer here:

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:

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"

回答1:

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() 



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!