我正在嘗試對包含數值資料列的一組資料完成主成分分析。
假設這樣的資料集(實際上我有一個預配置的資料框,如果是為了可重復性,則為這個):
v1 <- c(1,2,3,4,5,6,7)
v2 <- c(3,6,2,5,2,4,9)
v3 <- c(6,1,4,2,3,7,5)
dataset <-data.frame(v1,v2,v3)
row.names(dataset) <-c('New York', 'Seattle', 'Washington DC', 'Dallas', 'Chicago','Los Angeles','Minneapolis')
我已經運行了主成分分析,并成功繪制了它:
pca=prcomp(dataset,scale=TRUE)
plot(pca$x[,1], pca$x[,2],
xlab="First PC",ylab="Second PC")
text(pca$x[,1], pca$x[,2],cex=0.7,pos=3,col="darkgrey")
然而,我想要做的是根據城市對我的資料點進行顏色編碼,即我的資料集的行名稱。我也想使用這些城市(即行名)作為標簽。
我嘗試了以下方法,但都沒有奏效:
## attempt 1 - I get row labels, but no chart
plot(pca$x[,1], pca$x[,2],col=rownames(dataset),pch=rownames(dataset),
xlab="First PC",ylab="Second PC")
text(pca$x[,1], pca$x[,2],labels=rownames(dataset),cex=0.7,pos=3,col="darkgrey")
## attempt 2
datasetwithcity = rownames_to_column(dataset, var = "city")
head(datasetwithcity)
OnlyCities=datasetwithcity[,1]
OnlyCities
# this didn't work:
City_Labels=as.numeric(OnlyCities)
head(City_Labels)
# gets city labels, but loses points and no colour
plot(pca$x[,1], pca$x[,2],col=City_Labels,pch=City_Labels,
xlab="First PC",ylab="Second PC")
text(pca$x[,1], pca$x[,2],labels=rownames(dataset),
cex=0.7,pos=3,col="darkgrey")
uj5u.com熱心網友回復:
有許多不同的方法可以做到這一點。
在基礎 R 中,您可以執行以下操作:
plot(pca$x[,1], pca$x[,2],
xlab="First PC",ylab="Second PC", col = seq(nrow(pca$x)),
xlim = c(-2.5, 2.5), ylim = c(-2, 2))
text(pca$x[,1], pca$x[,2],cex=0.7,pos=3,col="darkgrey")
text(x = pca$x[,1], y = pca$x[,2], labels = rownames(pca$x), pos = 1)

就個人而言,我認為使用ggplot. 一旦習慣了語法,代碼也會更容易閱讀。
library(ggplot2)
df <- as.data.frame(pca$x)
df$city <- rownames(df)
ggplot(df, aes(PC1, PC2, color = city))
geom_point(size = 3)
geom_text(aes(label = city) , vjust = 2)
lims(x = c(-2.5, 2.5), y = c(-2, 2))
theme_bw()
theme(legend.position = "none")

由reprex 包( v2.0.0 )于 2021 年 10 月 28 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/341307.html
標籤:r
下一篇:如何修改和覆寫大檔案?
