ggnet: Grayscale node color for continuous node attributes?

426 views Asked by At

In ggnet2, I am struggling to add grayscale coloring to nodes based on continuous node attributes. Here are 2 variables for illustration:

> get.vertex.attribute(netshenzhen,"day")
# num [1:235] 47 17 16 12 18 48 42 15 20 38 ...

> str(get.vertex.attribute(netshenzhen,"source"))
# chr [1:235] "Traveled to Hubei" "Traveled to Hubei" "Traveled to Hubei" ...

If I type ggnet2(netshenzhen, label = T,color = "day"), here is the graph that's generated. But "day" is a continuous variable that I'd like to add grayscale on (darker color for more "days"). Also, I cannot figure out where this palette is coming from, and I get similar results if I attach other continuous attributes in the data.

network plot with a continuous variable day

If I use a factor instead, it works as introduced in the ggnet2 package. But I'd really like to add a continuous node attribute to grayscale.

network plot with a factor variable source

I've seen hand-coding solutions for this using statnet's own visualization tool. But I'd like to know if there're simple(r) solutions using ggnet?

I'm not very adept at R or programming. So sample codes with line-to-line comments/explanations are highly appreciated. Thank you!

1

There are 1 answers

0
Fr. On

Hi ~ It looks like you have inverted the two plots in your question: the second one is what you get if you do not pass a factor variable like your source variable.

The grayscale coloring of the nodes is what happens by default if you give ggnet2 a color variable that is not made of color names.

Below is how to match a continuous (numeric) variable like day to grayscale colors, and then to pass that to ggnet2. The line you are interested in is the one that creates the day_gray vertex attribute.

library(GGally)
library(network)

n <- network(sna::rgraph(10))
network.vertex.names(n) <- sample(letters, 10)

n %v% "day" <- sample(1:10, 10)
n %v% "day_gray" <- gray.colors(10)[ n %v% "day" ]

ggnet2(n, label = TRUE, color = "day_gray")

For more flexible solutions (in case you need something more advanced than what the above does), I'd recommend the ggraph package, or the ggnetwork package.