如何更改R中db-RDA三重图上点的颜色?

wh6knrhe  于 2023-02-01  发布在  其他
关注(0)|答案(1)|浏览(226)

问:我正在为我的基于距离的RDA结果构建一个三重图,在R,library(vegan)。我可以得到一个三重图来构建,但不能弄清楚如何使我的网站的颜色根据它们的位置不同。代码如下。

#running the db-RDA 
spe.rda.signif=capscale(species~canopy+gmpatch+site+year+Condition(pair), data=env, dist="bray")

#extract % explained by first 2 axes
perc <- round(100*(summary(spe.rda.signif)$cont$importance[2, 1:2]), 2)

#extract scores (coordinates in RDA space)
sc_si <- scores(spe.rda.signif, display="sites", choices=c(1,2), scaling=1)
sc_sp <- scores(spe.rda.signif, display="species", choices=c(1,2), scaling=1)
sc_bp <- scores(spe.rda.signif, display="bp", choices=c(1, 2), scaling=1)

#These are my location or site names that I want to use to define the colours of my points
site_names <-env$site
site_names

#set up blank plot with scaling, axes, and labels
plot(spe.rda.signif,
scaling = 1, 
type = "none", 
frame = FALSE,
xlim = c(-1,1),
ylim = c(-1,1),
main = "Triplot db-RDA - scaling 1",
xlab = paste0("db-RDA1 (", perc[1], "%)"),
ylab = paste0("db-RDA2 (", perc[2], "%)")
)

#add points for site scores - these are the ones that I want to be two different colours based on the labels in the original data, i.e., env$site or site_names defined above. I have copied the current state of the graph
points(sc_si,
pch = 21, # set shape (here, circle with a fill colour)
col = "black", # outline colour
bg = "steelblue", # fill colour
cex = 1.2) # size

电流图

我可以添加物种名称和箭头来预测环境,但我只是停留在如何改变站点点的颜色来反映它们的位置(我在原始数据中定义了两个位置)。我可以用文本标记它们,但这很混乱。
任何帮助感激不尽!
我试过用site_name来区分点的形状和颜色,但是没有成功。

pkwftd7m

pkwftd7m1#

如果您只有几个组(在您的情况下是两个),您可以将该组作为因子(在plot调用中)。在R中,因子表示为“幕后”整数-您可以使用简单整数表示最多8种基本R颜色:

set.seed(123)
df <- data.frame(xvals = runif(100),
                 yvals = runif(100),
                 group = sample(c("A", "B"), 100, replace = TRUE))

plot(df[1:2], pch = 21, bg = as.factor(df$group), 
     bty = "n", xlim = c(-1, 2), ylim = c(-1, 2))
legend("topright", unique(df$group), pch = 21, 
       pt.bg = unique(as.factor(df$group)), bty = "n")

如果您有超过8个组,或者如果您想定义自己的颜色,您可以简单地创建一个长度为您的组的颜色矢量,并仍然使用相同的因子方法,但有一些轻微的调整:

# data with 10 groups
set.seed(123)
df <- data.frame(xvals = runif(100),
                 yvals = runif(100),
                 group = sample(LETTERS[1:10], 100, replace = TRUE))

# 10 group colors
ccols <- c("red", "orange", "blue", "steelblue", "maroon",
                "purple", "green", "lightgreen", "salmon", "yellow")

plot(df[1:2], pch = 21, bg = ccols[as.factor(df$group)], 
     bty = "n", xlim = c(-1, 2), ylim = c(-1, 2))
legend("topright", unique(df$group), pch = 21, 
       pt.bg = ccols[unique(as.factor(df$group))], bty = "n")

相关问题