使用ggplot2为分组设置自定义颜色

10
我将尝试使用下面的代码使用ggplot2绘制线性判别图:
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

这段代码给出了如下的LDA图形, enter image description here 但我想为三个种群改变颜色,因此我修改了上面的代码,如下所示,
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

但是这段代码会报错美学必须是长度为1或与数据相同(150): x、y、colour。有没有办法可以解决这个问题?
1个回答

16

您需要将color映射到Species变量,然后使用scale_color_manual(而不是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

最好使用Set2(色盲安全,适合打印)来自ColorBrewer
p <- ggplot(data = plot.data, aes(x = X, y = Y, color = Species)) +
  geom_point() +
  scale_color_brewer(palette = "Set2") +
  theme_bw()
p

这段文字是由reprex包(版本为v0.2.1.9000)于2019年03月10日创建的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接