Electrino
Electrino

Reputation: 2900

Create a ggplot2 legend based on groups in R?

This seems like it should be easy.. but im struggling to find an answer. Basically, Im creating a plot in ggplot2 and colouring the points based on which group they belong to. For example:

library(ggplot2)
#Create some data
X <- c(10.59, 15.74, 5, 18, 7, 16.8, 2, 10, 15.5, 12)
Y <- c(2, 1.34, 1.27, 1.1, 2.22, 1.24, 2.11, 2.52, 0.96, 1.08)
df <- data.frame(X, Y)

# Create groups
groupZ <- c(1,1,1,1,1,1,2,2,2,2)
df$group <- groupZ

library(grDevices)
# Create colours for groups
colrs <- adjustcolor(c("red", "blue")) 
colorX <- colrs[groupZ]

# Plot
ggplot(df, aes(x = X, y = Y)) +
geom_point(size = Y*5, col = colorX) 

The code will produce something like this: plot coloured by group

What I want to do is create a legend that would consist of 2 circles (one red, one blue) to indicate which group each point comes from. Any suggestions as to how I would achieve this?

Upvotes: 0

Views: 186

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389325

One way would be to create a factor column for groups and use it in color of aes. You can then assign colors of your choice using scale_color_manual.

library(ggplot2)
X <- c(10.59, 15.74, 5, 18, 7, 16.8, 2, 10, 15.5, 12)
Y <- c(2, 1.34, 1.27, 1.1, 2.22, 1.24, 2.11, 2.52, 0.96, 1.08)
df <- data.frame(X, Y)
df$group <- factor(c(1,1,1,1,1,1,2,2,2,2))


# Plot
ggplot(df, aes(x = X, y = Y, color = group)) +
  geom_point(size = Y*5) +
  scale_color_manual(values = c('red', 'blue'))

enter image description here

Upvotes: 1

Related Questions