简体   繁体   English

控制R图中的颜色

[英]Control color in r plot

The output of nestednodf, a function of package vegan, can be easily plotted. nestednodf的输出(软件包vegan的功能)可以很容易地绘制出来。 I'd like to highlight selected rows in a different color but I don't know how to specify it in a single plot. 我想用不同的颜色突出显示选定的行,但是我不知道如何在单个图中指定它。 Say that I want rows 1,3 and 5 in blue and rows 2 and 4 in red (default color). 假设我要蓝色的行1,3和5和红色的行2和4(默认颜色)。 This code allows to overlap a second plot with rows 1,3,5 in blue but doesn't insert the selected rows in the first one: 此代码允许将第二个绘图与蓝色的行1,3,5重叠,但不会在第一行中插入选定的行:

library(vegan)
df=data.frame(a=c(0,1,1,1,0), b=c(1,0,0,0,1), c=c(1,1,1,1,0), d=c(1,0,1,0,1), e=c(0,0,0,1,1))
plot(nestednodf(df))
plot(nestednodf(df[c(1,3,5),]), col='blue', add=T)

Is there any way to control row color? 有什么方法可以控制行颜色? Something like this: 像这样:

plot(nestednodf(df), row.col=c('blue', '', 'blue', '', 'blue'))

You can view the source of the function by entering vegan:::plot.nestednodf . 您可以通过输入vegan:::plot.nestednodf来查看函数的源代码。 There's not really an opportunity two tweak row colors. 几乎没有机会调整两种行颜色。 However you can see the function is pretty simple so you can write your own version 但是您可以看到该函数非常简单,因此您可以编写自己的版本

myplot <- function (x, col = "red", names = FALSE, ...) 
{
    z <- x$comm
    z <- t(z[nrow(z):1, ])

    if (length(col) == 1) 
        col <- c(NA, col)
    else if ( length(col)>1) {
        z <- z*((col(z)-1)%%2+1)
    }
    image(z, axes = FALSE, col = col, ...)
    box()
    if (length(names) == 1) 
        names <- rep(names, 2)
    if (names[1]) {
        axis(2, at = seq(1, 0, len = ncol(z)), labels = rev(colnames(z)), 
            las = 2, ...)
    }
    if (names[2]) {
        axis(3, at = seq(0, 1, len = nrow(z)), labels = rownames(z), 
            las = 2, ...)
    }
}

Here I just added a line to change the colors to be alternating between the values specified. 在这里,我仅添加了一行以更改颜色,以在指定的值之间交替。 Compare 相比

plot(nestednodf(df))
myplot(nestednodf(df), col=c(NA,'red','blue'))

在此处输入图片说明

Note that I pass three colors because the first is used for the "0" values in the matrix 请注意,我传递了三种颜色,因为第一种用于矩阵中的“ 0”值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM