向R中的ggplot2中的折线图添加第二个图例 [英] Adding a second legend to line chart in ggplot2 in R

查看:108
本文介绍了向R中的ggplot2中的折线图添加第二个图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下非常简单的数据集,用多线折线图表示.数据集:

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)

因此,我正在ggplot2中使用以下函数来创建此数据集的多折线图:

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)

我得到的图表如下:

这绝对没问题.现在,我想添加另一个图例,该图例应另外显示实线-foo2,虚线-foo,虚线-foo1".基本上是我在函数中添加的线型".如何在图中添加第二个图例?谢谢.

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.

我还尝试了

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"

推荐答案

您的数据应首先采用整洁的格式,以便有效利用 ggplot :

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

这篇关于向R中的ggplot2中的折线图添加第二个图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆