Ammar Sabir Cheema
Ammar Sabir Cheema

Reputation: 990

Custom colors for groups using ggplot2

I am trying to plot linear discriminant plot using ggplot2 using the code given below:

require(MASS) 
require(ggplot2) 
data("iris")
my.data <- iris
model <- lda(formula = Species ~ ., data = my.data)
data.lda.values <- predict(model)
plot.data <- data.frame(X=data.lda.values$x[,1], Y=data.lda.values$x[,2], Species=my.data$Species)
p <- ggplot(data=plot.data, aes(x=X, y=Y)) +
geom_point(aes(color=Species)) +
theme_bw()
p

This code gives lda plot as given below, enter image description here

But I want to change the colors for the three populations for which I have modified the above code as given below,

my_colors <- c("yellow","magenta","cyan")
p <- ggplot(data=plot.data, aes(x=X, y=Y,color=my_colors)) +
geom_point() +
scale_fill_manual(values=my_colors) 
p

But this code gives error Aesthetics must be either length 1 or the same as the data (150): x, y, colour. Is there a way I can achieve this ?

Upvotes: 10

Views: 12807

Answers (1)

Tung
Tung

Reputation: 28331

You need to map color to Species variable then use scale_color_manual (not fill)

require(MASS)
require(ggplot2)

data("iris")
my.data <- iris
model <- lda(formula = Species ~ ., data = my.data)
data.lda.values <- predict(model)
plot.data <- data.frame(X = data.lda.values$x[, 1], Y = data.lda.values$x[, 2], Species = my.data$Species)

my_colors <- c("yellow", "magenta", "cyan")
p <- ggplot(data = plot.data, aes(x = X, y = Y, color = Species)) +
  geom_point() +
  scale_color_manual(values = my_colors) +
  theme_bw()
p

Probably better to use Set2 (colorblind safe, print friendly) from ColorBrewer

p <- ggplot(data = plot.data, aes(x = X, y = Y, color = Species)) +
  geom_point() +
  scale_color_brewer(palette = "Set2") +
  theme_bw()
p

Created on 2019-03-10 by the reprex package (v0.2.1.9000)

Upvotes: 16

Related Questions