我在 R 中有一個資料框,其中包含 PCA 資料,大致如下所示:
| 討厭的人 | 電腦1 | 電腦2 | 電腦3 |
|---|---|---|---|
| 一 | 2.46 | 2.57 | 1.366962e-15 |
| 二 | -3.47 | 0.84 | 3.053113e-16 |
| 三 | 1.01 | -3.40 | 7.077672e-16 |
你可以用這個加載確切的變數:
structure(list(obsnames = c("one", "two", "three"), PC1 = c(2.46310908247957,
-3.46877162330214, 1.00566254082257), PC2 = c(2.56831624877025,
0.836571395923965, -3.40488764469422), PC3 = c(1.36696209906972e-15,
3.05311331771918e-16, 7.07767178198537e-16), `Sample Size` = c(48L,
74L, 52L)), row.names = c("one", "two", "three"), class = "data.frame")
現在。我試圖通過僅使用那些允許“填充”美學(21-25 iirc)的形狀來使用 ggplo2 geom_point 繪制此 PCA。但是,我無法創建圖例以使其與圖中顯示的形狀和顏色相匹配。我放棄了自己解決這個問題,而且我覺得這很奇怪,因為我幾乎都是手動喂它的。這是我的繪圖線:
len <- length(pca_data$obsnames)
ggplot(pca_data, aes_string(x=x, y=y))
geom_point(shape = rep_len(c(21, 22, 23, 24, 25) length.out =
len),
color = "black", size = 3, aes(fill=obsnames))
theme_bw()
theme(legend.position="right")
xlab(label_x)
ylab(label_y)
ggtitle(main)
theme(plot.title = element_text(hjust = 0, face="bold"))
geom_hline(aes(0), size=.2,yintercept=0)
geom_vline(aes(0), size=.2,xintercept=0)
coord_equal()
geom_text(data=datapc, aes(x=v1, y=v2, label=varnames), size = 3, vjust=0.3, color="grey", fontface="bold")
geom_segment(data=datapc, aes(x=0, y=0, xend=v1, yend=v2), color="grey", linetype="dotted")
scale_fill_manual(values = rep_len(c("red", "blue", "green", "orange", "yellow", "purple", "pink", "light blue", "white", "black", "gold"), length.out = len))
guides(fill=guide_legend(override.aes=list(shape=rep_len(c(21, 22, 23, 24, 25), length.out = len))))
輸出以下圖:

如你看到的。圖例將“二”顯示為綠色菱形,而實際上它應該是綠色方塊。此外,當我碰巧使用與形狀向量中的形狀相同數量的點(obnames)時:c(21, 22, 23, 24, 25); 也就是說,5,那么問題就不會出現。但我真的不明白我做錯了什么......
uj5u.com熱心網友回復:
如果你讓ggplot處理它,這是最好的事情之一;也就是說,通過確保將形狀/填充規范放入aes(). 為了這個演示,我已經減少了你的情節的特征;重新添加它們應該不會太難。更重要的是,請注意我創建了一個命名向量作為;的values引數傳遞scale_*_manual()。這可確保值和標簽以正確的方式匹配:
len <- length(pca_data$obsnames)
shapes <- rep_len(x = c(21, 22, 23, 24, 25), length.out = len)
ptcols <- rep_len(x = c(
"red", "blue", "green", "orange", "yellow", "purple", "pink",
"light blue", "white", "black", "gold"
), length.out = len)
names(shapes) <- pca_data$obsnames
names(ptcols) <- pca_data$obsnames
ggplot(data = pca_data, mapping = aes(x = PC1, y = PC2))
geom_point(aes(shape = obsnames, fill = obsnames), color = "black")
scale_fill_manual(values = ptcols)
scale_shape_manual(values = shapes)
theme_bw()

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/355829.html
