使用 ggplot,如何在属于一个组的散点图中构建点?
Using ggplot, How could I frame points in a scatter plot that belong to a group?
在我的数据中,我将每个观察结果分类为一组。我想在散点图中绘制数据并框出每组以显示差异。据我所知,如果你有 Kmens、pam 或 clara 的聚类数据,R 中有几个函数可以做到这一点(例如 ggfortify 包中的 autoplot(),factoextra 包中的 fviz_cluster() 或 clusplot( ) 在群集包中)。作为示例,我使用 iris 数据集和包 ggfortify。
library(ggplot2)
library(ggfortify)
#dimension reduction
IrisPrinComp <- princomp(formula=~Sepal.Length +Sepal.Width +Petal.Length +Petal.Width, data = iris )
IrisWithPrinComp <- cbind(iris, IrisPrinComp$scores)
IrisWithPrinComp$FactorSpecies <- factor(IrisWithPrinComp$Species)
#Plot
ggplot(data=IrisWithPrinComp, aes(x=Comp.1, y=Comp.2, color=FactorSpecies))+geom_point()
Iris principal components scatter plot
使用 ggfortify 我几乎得到了我想要的,除了集群错误分类了一些观察结果:
Irisclusters <- kmeans(x = IrisWithPrinComp[,c("Comp.1", "Comp.2")], centers = 3, iter.max = 20, nstart = 5)
IrisWithPrinComp$Cluster <- factor(Irisclusters$cluster)
autoplot(Irisclusters, data = IrisWithPrinComp, frame=T)
Framed kmeans scatter plot
您可以使用 ggalt
包中的 geom_encircle
library(dplyr)
library(ggplot2)
library(tibble)
# devtools::install_github("hrbrmstr/ggalt")
library(ggalt)
princomp(formula = ~Sepal.Length + Sepal.Width + Petal.Length + Petal.Width,
data = iris) %>%
fortify() %>%
add_column(FactorSpecies = factor(iris$Species)) %>%
ggplot(aes(x = Comp.1, y = Comp.2, color = FactorSpecies)) +
geom_point() +
geom_encircle(aes(group = FactorSpecies))
在我的数据中,我将每个观察结果分类为一组。我想在散点图中绘制数据并框出每组以显示差异。据我所知,如果你有 Kmens、pam 或 clara 的聚类数据,R 中有几个函数可以做到这一点(例如 ggfortify 包中的 autoplot(),factoextra 包中的 fviz_cluster() 或 clusplot( ) 在群集包中)。作为示例,我使用 iris 数据集和包 ggfortify。
library(ggplot2)
library(ggfortify)
#dimension reduction
IrisPrinComp <- princomp(formula=~Sepal.Length +Sepal.Width +Petal.Length +Petal.Width, data = iris )
IrisWithPrinComp <- cbind(iris, IrisPrinComp$scores)
IrisWithPrinComp$FactorSpecies <- factor(IrisWithPrinComp$Species)
#Plot
ggplot(data=IrisWithPrinComp, aes(x=Comp.1, y=Comp.2, color=FactorSpecies))+geom_point()
Iris principal components scatter plot 使用 ggfortify 我几乎得到了我想要的,除了集群错误分类了一些观察结果:
Irisclusters <- kmeans(x = IrisWithPrinComp[,c("Comp.1", "Comp.2")], centers = 3, iter.max = 20, nstart = 5)
IrisWithPrinComp$Cluster <- factor(Irisclusters$cluster)
autoplot(Irisclusters, data = IrisWithPrinComp, frame=T)
Framed kmeans scatter plot
您可以使用 ggalt
包中的 geom_encircle
library(dplyr)
library(ggplot2)
library(tibble)
# devtools::install_github("hrbrmstr/ggalt")
library(ggalt)
princomp(formula = ~Sepal.Length + Sepal.Width + Petal.Length + Petal.Width,
data = iris) %>%
fortify() %>%
add_column(FactorSpecies = factor(iris$Species)) %>%
ggplot(aes(x = Comp.1, y = Comp.2, color = FactorSpecies)) +
geom_point() +
geom_encircle(aes(group = FactorSpecies))