2017-08-14 33 views
1

我想使用R stat模塊prcomp和ggplot2進行pca分析,示例數據如下所示。對於每個汽車模型,有三列中的數據,到目前爲止,我能夠使用下面給出的代碼生成該圖。ggplot幾何點,修改文本

DF:

> head(car.df) 
    honda_1_smp honda_2_smp honda_3_smp audi_1_smp audi_2_smp audi_3_smp merc_1_smp merc_2_smp 
s1 0.000289 0.000000 0.076095 0.056965 0.030314 0.000000 0.000000 0.028548 
s2 1.588724 1.678821 0.795915 0.552910 0.503845 0.248782 0.201806 2.324172 
s3 0.067802 0.068452 0.082904 0.014259 0.038896 0.044144 0.003634 0.167235 
s4 0.000000 0.000000 0.000000 0.000000 0.000000 0.008724 0.000000 0.000000 
s5 0.822612 1.137569 0.008302 0.025600 0.000000 0.000000 0.000000 0.000000 
s6 0.025091 0.096847 0.000000 0.031416 0.024999 0.000000 0.012987 0.000000 

代碼:

carpca = prcomp(t(car.df), center=T) 
summary(carpca) 
car12 = data.frame(PC1=carpca$x[,1], PC2= carpca$x[,2], type=rownames(carpca$x)) 
ggplot(car12, aes(x=PC1 , y=PC2 , col=type)) + 
    geom_point() + geom_text(aes(label = type), hjust=0, vjust=0) + 
    xlab("PC1 89%") + ylab("PC2 77%") + ggtitle("car") 

情節enter image description here

問題

如何組我的所有複製標題爲一體的顏色和形狀的情節和傳說。 含義:對於audi和merc,每個本田都會有相同的顏色和形狀。

+1

我相信,在'car12',創建另一個列'brand'表明品牌,然後用'顏色=品牌,外形=在'aes'將工作brand'。 –

回答

2

我會使用正則表達式(gsub)從「type」屬性中刪除複製標識。

car12 = data.frame(PC1=carpca$x[,1], PC2= carpca$x[,2], type=gsub("_.*$", "", rownames(carpca$x))) 
ggplot(car12, aes(x=PC1 , y=PC2 , col=type)) + 
    geom_point() + geom_text(aes(label = type), hjust=0, vjust=0) + 
    xlab("PC1 89%") + ylab("PC2 77%") + ggtitle("car") 

enter image description here

+0

它像魅力一樣,我怎麼改變每種類型的形狀 – sbradbio

+1

也許你可以用這種方式繪製你的數據...'ggplot(car12,aes(x = PC1,y = PC2,col = type))+ geom_point (aes(shape = type))+ annotate(geom =「text」,x = car12 $ PC1,y = car12 $ PC2, label = car12 $ type,hjust = -0.1,vjust = -0.1)+ xlab (「PC1 89%」)+ ylab(「PC2 77%」)+ ggtitle(「汽車」) ' –

+0

這工作,除了我原來的數據有超過6個變量,我得到錯誤'警告消息: 1 :形狀調色板可以處理最多6個離散值,因爲比6更多地變得難以區分;你有7.手動指定 形狀,如果你必須有它們' – sbradbio