Search code examples
rggplot2legendscatter-plot

How to add legend to scatter plot in ggplot?


I have assigned a shape and color to each point, and I want to draw the legend according to the group data, but I can't add the legend..

library(datasets)
library(tidyverse)
library(reshape2)

name <- c("S1","S1","S1","S2","S2","S3","S3","S3","S4","S4","S5")
x <- c(1,5,9,8,5,6,7,4,3,6,4)
y <- c(3,8,9,5,7,5,3,8,9,3,4)
Shape <- c(21,21,21,22,22,23,23,23,24,24,25)
Color <- c("red","red","red","blue","blue","green","green","green","purple","purple","black")

df <- data.frame(x,y,name,Shape,Color)

graph1 <- ggplot(df,aes(x,y,fill = Color, shape = Shape))+
  geom_point(size = 4)+
  scale_shape_identity()+
  scale_fill_identity()
graph1

the x and y is the main data. The name is the group. The Shape and Color is the shape and color I assigned for all those point. How to draw a legend according to the group?


Solution

  • I think you are looking for:

    ggplot(df, aes(x = x ,y = y, fill = name, shape = name)) +
      geom_point(size = 4) +
      scale_fill_manual(values = unique(df$Color)) +
      scale_shape_manual(values = unique(df$Shape))
    

    enter image description here