force-directed graph using qgraph label colors don't match the nodes

237 Views Asked by At

I'm using qgraph to plot a network graph from a distance matrix and I can't get the labels to match the colours of the nodes in the graph.

My code is as follows:

clr <- function(x) {
  known <- c(`Effluent`="seagreen", `Influent`="brown", `WWTP Animal`="skyblue",
             `Human`="red", `Aircraft`="lemonchiffon")
  known[x]
}

x <- read.table("Path/to/distance/matrix.tsv", sep="\t", header = T)
x <- 1 / as.matrix(x[,-1])


x_sub <- x[1:50,1:50]

grps <- data[,c("ID","Sample_type_grouped")]
grps <- grps[grps$ID %in% colnames(x_sub),]

grps <- grps[match(colnames(x_sub),grps[,"ID"]),"Sample_type_grouped"]

qgraph(x_sub, layout='spring', groups=grps, color=clr(grps))

Here is an image of the final result

Thanks for any help!

1

There are 1 best solutions below

0
On

It is hard to answer this without a reproducible example, but I think the problem is that you assign a color per node while also using the groups argument. If you use groups the color argument should only assign one color per group (so the length should be the number of groups). Here is an example dataset:

adj <- matrix(rnorm(10^2),10,10)
adj <- adj + t(adj)
groups <- c(rep("A",5),rep("B",5))

The following will not work:

library("qgraph")
qgraph(adj, groups = groups, color = ifelse(groups=="A","red","blue"))

As it doesn't show a blue node. This is because only the first two elements of color are used, which are both red. This does work:

qgraph(adj, groups = groups, color = c("red","blue"))