4

如何为我在树状图中添加的一些彩色条添加标签?

下面的代码将显示我为瞄准任务所做的两次尝试,将值1链接到红色,将值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"))

生成的图分别存在以下问题:

  • 用于彩色条的值是二进制的,但状态标签显示 4 个不同的值。

  • 中断定义明确,但链接到它们的颜色是错误的

  • 用于彩色条的值是二进制的,但状态标签显示 4 个不同的值(跳过没用)

这些地块是:

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

代码参考可在12 . 第一个链接显示如何添加标签,这对我不起作用,第二个链接显示如何添加彩条。

4

1 回答 1

6

以下dendextend小插曲可能会得到你想要的。我稍微改变了颜色,因为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 包(v0.2.0) 于 2018-03-03 创建。

编辑:另见此处现场演示

于 2018-03-03T22:10:33.597 回答