Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't add legend to ggplot2 figure – scale_color_manual() does nothing

The below is fully reproducible. I have the data frame

Deciles    P_pred      P_true
1          0.3366666   0.2586773
2          0.3531208   0.3151918
3          0.3692757   0.3379759
4          0.3898140   0.3886151
5          0.4183384   0.4487537
6          0.4577579   0.5008214
7          0.5134715   0.5796729
8          0.5940276   0.6359546
9          0.7087249   0.7242340
10         0.8592295   0.8133705

I want to plot both P_pred and P_true on the y-axis against Deciles in the same figure and add a legend as well. This is what I did

ggplot(data = averages, aes(x = as.integer(Deciles))) +
  scale_x_reverse(breaks = 10:1) +
  geom_line(aes(y = P_pred), color = 'darkred', size = 2) + 
  geom_line(aes(y = P_true), color = 'darkgreen', size = 2) +
  ylab('Probabilities') + 
  xlab('Deciles') +
  scale_color_manual(values = c('darkred','darkgreen'))

However, the legend is not appearing. What am I doing wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Move the color to your aes() and it works as expected

ggplot(data = averages, aes(x = as.integer(Deciles))) +
  scale_x_reverse(breaks = 10:1) +
  geom_line(aes(y = P_pred, color = 'darkred'), size = 2) + 
  geom_line(aes(y = P_true, color = 'darkgreen'), size = 2) +
  ylab('Probabilities') + 
  xlab('Deciles') +
  scale_color_manual(values = c('darkred','darkgreen'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading