我正在尝试使用下面给出的代码使用 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
Run Code Online (Sandbox Code Playgroud)
但我想更改三个群体的颜色,我已修改了上述代码,如下所示,
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
Run Code Online (Sandbox Code Playgroud)
但此代码给出错误Aesthetics must be either length 1 or the same as the data (150): x, y, color。有什么办法可以实现这个目标吗?
Tun*_*ung 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
Run Code Online (Sandbox Code Playgroud)

可能更好地使用Set2(色盲安全,打印友好)ColorBrewer
p <- ggplot(data = plot.data, aes(x = X, y = Y, color = Species)) +
geom_point() +
scale_color_brewer(palette = "Set2") +
theme_bw()
p
Run Code Online (Sandbox Code Playgroud)

由reprex 包于 2019-03-10 创建(v0.2.1.9000)
| 归档时间: |
|
| 查看次数: |
10843 次 |
| 最近记录: |