我如何为树形图中添加的一些彩色条添加标签?
下面的代码将显示我为瞄准任务所做的两次尝试,即将值 1 与颜色 red 和值相关联0 在彩色条的标签中为白色着色。
# replacing the graphic window parameter so the color bars would fit
par( oma = c(0,1,1,1), mgp = c(1,0.5,0), mar = c(10,2,2,2) )
# load necessary packages
library( squash )
library( dendextend )
# "initializatin"
data("mtcars")
myDend <- as.dendrogram(hclust(dist(mtcars)))
# creating the numeric & color matrix used for
# (attempted) labels & colors bars, respectively
myStatus <- cbind(mtcars$vs,mtcars$am)
myColors <- matrix(c("mintcream","firebrick3")[1 + myStatus],ncol = 2)
myColors <- matrix(c("mintcream","firebrick3")[1 + cbind(mtcars$vs,mtcars$am)],
ncol = 2)
# default function without trying to force the label to a particular design
plot(myDend)
cmap <- squash::makecmap( myStatus, n = 2,colFn = colorRampPalette(c("mintcream","firebrick3")))
vkey(cmap, "Status")
colored_bars(colors = myColors, dend = myDend, rowLabels = c("VS","AM"))
# >> attempt 1 << trying to force breaks to 0 and 1
plot(myDend)
cmap <- squash::makecmap( myStatus, n = 2,colFn = colorRampPalette(c("mintcream","firebrick3")), breaks = c(0,1))
vkey(cmap, "Status")
colored_bars(colors = myColors, dend = myDend, rowLabels = c("VS","AM"))
# >> attempt 2 << trying to force breaks to 0 and 1
plot(myDend)
cmap <- squash::makecmap( myStatus, n = 2,colFn = colorRampPalette(c("mintcream","firebrick3")))
vkey(cmap, "Status", skip = c(0.5))
colored_bars(colors = myColors, dend = myDend, rowLabels = c("VS","AM"))
生成的图分别具有以下问题:
用于彩色条的值是二进制,但 Status 标签显示4个不同的值。
中断定义明确,但链接的颜色错误
用于彩色条的值是二进制的,但状态标签显示4个不同的值(跳过没有做它的工作)
情节如下:
答案 0 :(得分:6)
关注dendextend
vignettes可能会得到你想要的。我稍微改变了颜色,因为mintcream
在白色背景上不好。
library(magrittr)
library(dendextend)
data("mtcars")
# Create the dendrogram, use default options
dend_mtcars <- mtcars %>%
dist %>%
hclust() %>%
as.dendrogram
# Set the plot margin: bottom, left, top & right
par(mar = c(10, 3, 3, 4) + 0.1,
xpd = NA) # allow content to go into outer margin
# Plot
plot(dend_mtcars)
# Setup the color bar based on $am & $vs
the_bars_am <- ifelse(mtcars$am, "firebrick3", "beige")
the_bars_vs <- ifelse(mtcars$vs, "firebrick3", "beige")
the_bars <- cbind(the_bars_vs, the_bars_am)
colored_bars(colors = the_bars, dend = dend_mtcars, rowLabels = c("vs", "am"))
# Add the legend manually
legend("topright", legend = c('0', '1'), pch = 15, pt.cex = 3, cex = 1.5, bty = 'n',
inset = c(-0.1, 0), # place outside
title = "Status",
col = c('beige', 'firebrick3'))
由reprex package(v0.2.0)创建于2018-03-03。