[英]In R when coloring a phylogenetic tree by a trait using tip.color(), how do you choose colors and add the legend?
我有一棵看起來像這樣的樹;
# Create tree
library(phytools)
sim.tree<-pbtree(n=18)
plot(sim.tree)
我有一個帶有我的特征的數據框(一個 class 因子的向量)像這樣着色;
# data frame with vector to color tree with
df<-data.frame(tip = paste0("t", 1:18),
vector.to.color.with = as.factor(c("<10", "10-20", "10-20", "10-20", "NA", "10-20",
"10-20", "10-20", "20-35", "<10", "10-20", "<10",
"35", "20-35", "<10", "NA", "10-20", "<10")))
在 SO 的大力幫助下,我能夠像這樣給提示標簽上色;
cols <- as.integer(df$vector.to.color.with[match(sim.tree$tip.label,df$tip)])
plot(sim.tree, tip.color = cols)
我現在想選擇自己的colors,加上圖例。 任何幫助是極大的贊賞。
這是一個帶有自定義 colors 的版本:
library(dplyr)
library(phytools)
## library(RColorBrewer)
# Create tree
df<-data.frame(tip = paste0("t", 1:18),
brk = as.factor(c("<10", "10-20", "10-20", "10-20", "NA", "10-20",
"10-20", "10-20", "20-35", "<10", "10-20", "<10",
"35", "20-35", "<10", "NA", "10-20", "<10"))) |>
mutate(color = recode(brk,
"<10" = "red",
"10-20" = "green",
"NA" = "gray",
"20-35" = "blue",
"35" = "black"))
## mutate(color = brewer.pal(6, "Set1")[brk])
set.seed(123)
sim.tree<-pbtree(n=18)
cols <- with(df, as.character(color[match(sim.tree$tip.label, tip)]))
plot(sim.tree, tip.color = cols, x.lim = c(0,3))
with(df,
legend(x=2.5, y=10,
legend = levels(brk),
## col = brewer.pal(6, "Set1"),
col = as.character(levels(color)),
pch = 20,
box.lwd = 1))
這里有一個RColorBrewer
的解決方案,它提供了已經很漂亮的調色板。
library(dplyr)
library(phytools)
library(RColorBrewer)
# Create tree
df<-data.frame(tip = paste0("t", 1:18),
brk = as.factor(c("<10", "10-20", "10-20", "10-20", "NA", "10-20",
"10-20", "10-20", "20-35", "<10", "10-20", "<10",
"35", "20-35", "<10", "NA", "10-20", "<10"))) |>
## mutate(color = recode(brk,
## "<10" = "red",
## "10-20" = "green",
## "NA" = "gray",
## "20-35" = "blue",
## "35" = "black"))
mutate(color = brewer.pal(6, "Set1")[brk])
set.seed(123)
sim.tree<-pbtree(n=18)
cols <- with(df, color[match(sim.tree$tip.label, tip)])
plot(sim.tree, tip.color = cols, x.lim = c(0,3))
with(df,
legend(x=2.5, y=10,
legend = levels(brk),
col = brewer.pal(6, "Set1"),
## col = as.character(levels(color)),
pch = 20,
box.lwd = 1))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.