gpt4 book ai didi

r - 如何在树状图中标记彩色条

转载 作者:行者123 更新时间:2023-12-02 03:07:38 24 4
gpt4 key购买 nike

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

下面的代码将显示我为瞄准任务所做的两次尝试,即将值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 个不同的值(跳过没有完成它的工作)

绘图如下:

enter image description here

enter image description here

enter image description here

代码的引用可在 中找到。 1 , 2 。第一个链接显示了如何添加标签,这对我来说不起作用,第二个链接显示了如何添加颜色条。

最佳答案

已关注 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于2018年3月3日创建(v0.2.0)。

编辑:另请参阅herelive demo

关于r - 如何在树状图中标记彩色条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49088627/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com