pineapple
pineapple

Reputation: 169

How can I add with ggplot the colored legend?

I have this dataframe and I want to plot with ggplot on x axis the result_df50$id column and on the y axis the columns result_df50$Sens and result_df50$Spec.

Also I want result_df50$Sens and result_df50$Spec to be displayed in different colors. The legend should also show the different colors of the columns.

> 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

So far I tried this and I am happy with it.

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

Now I just want to add the legend with the colors of each line. I tried fill, but R gives a warning and ignores this unknown aesthetics: fill.... How can I do this?

Upvotes: 0

Views: 45

Answers (1)

alex_555
alex_555

Reputation: 1102

This is because your dataset has the wrong format (wide). You'll have to convert it into long format to make it work as follows:

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

Is this what you want?

Upvotes: 1

Related Questions