[英]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.