R 如何添加彩色图例?

R 如何添加彩色图例?,r,ggplot2,legend,R,Ggplot2,Legend,我有这个数据框,我想用ggplot在x轴上绘制result_df50$id列,在y轴上绘制result_df50$Sens和result_df50$Spec列 另外,我希望result_df50$Sens和result_df50$Spec以不同的颜色显示。图例还应显示列的不同颜色 > result_df50 Acc Sens Spec id 1 12 51 15 1 2 24 78 28 2 3 31 86 32 3 4 78 23

我有这个数据框,我想用ggplot在x轴上绘制result_df50$id列,在y轴上绘制result_df50$Sens和result_df50$Spec列

另外,我希望result_df50$Sens和result_df50$Spec以不同的颜色显示。图例还应显示列的不同颜色

> result_df50
   Acc Sens Spec id
1   12   51   15  1
2   24   78   28  2
3   31   86   32  3
4   78   23   90  4
5   49   43   56  5
6   25   82   33  6
7    6   87    8  7
8   60   33   61  8
9   54    4   66  9
10   5   54    9 10
11   1   53    4 11
12   2   59    7 12
13   4   73    3 13
14  48   41   55 14
15  30   72   39 15
16  57   10   67 16
17  80   31   91 17
18  30   65   36 18
19  58   45   61 19
20  12   50   19 20
21  39   47   46 21
22  38   49   45 22
23   3   69    5 23
24  68   24   76 24
25  35   64   42 25
到目前为止,我尝试了这个,我很高兴

ggplot(data = result_df50) +
  geom_line(data= result_df50, aes(x = result_df50$id, y = result_df50$Spec), colour = "blue") + 
  geom_line(data= result_df50, aes(x = result_df50$id, y = result_df50$Sens), colour = "red") +
  labs(x="Number of iterations")
现在我只想添加带有每行颜色的图例。我试过填充,但R给出了一个警告,忽略了这个未知的美学:填充。。。。
我如何才能做到这一点?

这是因为数据集的格式不正确。您必须将其转换为长格式,以使其按如下方式工作:

result_df50 <-  read.table(text="Acc Sens Spec id
1   12   51   15  1
           2   24   78   28  2
           3   31   86   32  3
           4   78   23   90  4
           5   49   43   56  5
           6   25   82   33  6
           7    6   87    8  7
           8   60   33   61  8
           9   54    4   66  9
           10   5   54    9 10
           11   1   53    4 11
           12   2   59    7 12
           13   4   73    3 13
           14  48   41   55 14
           15  30   72   39 15
           16  57   10   67 16
           17  80   31   91 17
           18  30   65   36 18
           19  58   45   61 19
           20  12   50   19 20
           21  39   47   46 21
           22  38   49   45 22
           23   3   69    5 23
           24  68   24   76 24
           25  35   64   42 25")

# conversion to long format
library(reshape2)
result_df50 <- melt(result_df50, id.vars=c("Acc", "id"))

head(result_df50)
#   Acc id variable value
# 1  12  1     Sens    51
# 2  24  2     Sens    78
# 3  31  3     Sens    86
# 4  78  4     Sens    23
# 5  49  5     Sens    43
# 6  25  6     Sens    82

# your plot
ggplot(data = result_df50, aes(x = id, y =value , color=variable)) +
  geom_line() + 
  labs(x="Number of iterations")+
  scale_color_manual(values=c("red", "blue")) # in case you want to keep your colors

这就是你想要的吗?

谢谢你的评论!我如何使用你的答案绘制两条线,这将是y轴上的Sens和Spec?正是我的示例所显示的方式。首先,您必须更改数据格式,以便Spec和Sens成为新列中的两个因子级别/字符。在ggplot美学的color参数中指定该列后,这两行都会按照您想要的方式显示。复制并粘贴我的整个示例你向下滚动了吗?试试看。应该行的。好吧,我没看到其他的。。。刚试过,效果不错。谢谢您的示例数据相当长,这使得示例比必须的要长。你只需要转换和绘图部分,它们很短。我的真实数据更长…再次感谢!