[英]How to plot filled points and confidence ellipses with the same color using ggplot in R?
我想 plot 来自判别式 Function 分析的图表,其中点必须有黑色边框并填充特定的 colors 和置信椭圆必须填充相同的颜色。 使用下面的代码,我几乎得到了我想要的图形,除了点没有黑色边框:
library(ggplot2)
library(ggord)
library(MASS)
data("iris")
set.seed(123)
linear <- lda(Species~., iris)
linear
dfaplot <- ggord(linear, iris$Species, labcol = "transparent", arrow = NULL, poly = FALSE, ylim = c(-11, 11), xlim = c(-11, 11))
dfaplot +
scale_shape_manual(values = c(16,15,17)) +
scale_color_manual(values = c("#00FF00","#FF00FF","#0000FF")) +
theme(legend.position = "none")
我可以使用以下代码在点上添加黑色边框,但随后置信椭圆变为黑色。
dfaplot +
scale_shape_manual(values = c(21,22,24)) +
scale_color_manual(values = c("black","black","black")) +
scale_fill_manual(values = c("#00FF00","#FF00FF","#0000FF")) +
theme(legend.position = "none")
我想保留第一个图中的椭圆,但保留第二个图中的点。 但是,我无法弄清楚如何做到这一点。 如果有人对如何做到这一点有建议,我将不胜感激。 我正在使用“ggord”package,因为我学会了如何使用它来运行分析,但是如果有人对如何仅使用 ggplot 执行相同的操作有任何建议,那就没问题了。
这大致复制了ggord
中发生的事情。 查看 package 的源代码,椭圆在ggord
中的实现方式与下面的不同,因此差异很小。 如果这很重要,您可以查看源并进行更改。 默认情况下, geom_point
没有填充属性。 所以我们将形状设置为字符类型,然后在geom_point()
中指定color = 'black'
。 完整代码(包括投影原始数据)如下。
set.seed(123)
linear <- lda(Species~., iris)
linear
# Get point x, y coordinates
df <- data.frame(predict(linear, iris[, 1:4]))
df$species <- iris$Species
# Get explained variance for each axis
var_exp <- 100 * linear$svd ^ 2 / sum(linear$svd ^ 2)
ggplot(data = df,
aes(x = x.LD1,
y = x.LD2)) +
geom_point(aes(fill = species,
shape = species),
size = 4) +
stat_ellipse(aes(color = species),
level = 0.95) +
ylim(c(-11, 11)) +
xlim(c(-11, 11)) +
ylab(paste("LD2 (",
round(var_exp[2], 2),
"%)")) +
xlab(paste("LD1 (",
round(var_exp[1], 2),
"%)")) +
scale_color_manual(values = c("#00FF00","#FF00FF","#0000FF")) +
scale_fill_manual(values = c("#00FF00","#FF00FF","#0000FF")) +
scale_shape_manual(values = c(21, 22, 24)) +
coord_fixed(1) +
theme_bw() +
theme(
legend.position = "none"
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.