Home > Software engineering >  How to add legend to scatter plot in ggplot?
How to add legend to scatter plot in ggplot?

Time:10-27

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?

CodePudding user response:

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

CodePudding user response:

You were missing aes parameter color :-)

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, color = name, shape = Shape))  
  geom_point(size = 4)  
  scale_shape_identity()  
  scale_fill_identity()
graph1

You will note that using the group (name) as the basis for the legend makes this plot confusing, but in any case, you can add the color param to ensure that your legend is rendered.

plot image

if you use Color as the value for the color parameter you get the following:

better param for legend

  • Related