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

How do I add legend label to a new color point in ggplot?

I have a plot that looks like this:

library('ggplot2')

df = data.frame(Sepal.Width = 5.6, Sepal.Length = 3.9) 

ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length, col = Species)) +
  geom_point() +
  geom_point(data = df, col = 'blue')

I want to label point blue in the legend. How do I do that?

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 :

One way is to assign a color with some name in aes for the point. Then, you can change the color and name manually in scale_color_manual.

library(tidyverse)

ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length, col = Species)) +
  geom_point() +
  geom_point(aes(x = Sepal.Width, y = Sepal.Length, colour = 'Sepal.Width'),
             data = df) +
  scale_color_manual(
    values = c(
      "Sepal.Width" = "blue",
      "setosa" = "red",
      "versicolor" = "darkgreen",
      "virginica" = "orange"
    ),
    labels = c('New Point', "setosa", "versicolor", "virginica")
  )

Output

enter image description here

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