0

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!

Sushiroll
  • 37
  • 6
  • can you `dput` the `grps` object immediately before the `qgraph()` call, and also show the results of `clr(grps)`? – Paul Stafford Allen Jan 13 '23 at 10:19
  • looking at the pdf for the package, try including `legend.mode = "groups"`? – Paul Stafford Allen Jan 13 '23 at 10:24
  • Hey Paul, Thanks for the reply, dput(grps) returns this: c("Effluent", "Influent", "Influent", "Effluent", "Effluent", "Effluent" ....) While clr(grps) gives this: Effluent Influent Influent Effluent Effluent Effluent "seagreen" "brown" "brown" "seagreen" "seagreen" "seagreen" Influent Effluent Influent Influent Influent Effluent "brown" "seagreen" "brown" "brown" "brown" "seagreen" Influent Influent – Sushiroll Jan 13 '23 at 13:39
  • I had tried with legend.mode="groups" and nothing changed. – Sushiroll Jan 13 '23 at 13:40
  • can you share a reproducible example please? – Paul Stafford Allen Jan 13 '23 at 13:45

1 Answers1

0

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"))
Sacha Epskamp
  • 46,463
  • 20
  • 113
  • 131