简体   繁体   中英

Control color in r plot

The output of nestednodf, a function of package vegan, can be easily plotted. 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). 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:

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 . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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