I am trying to plot the network g
:
> g
Network attributes:
vertices = 866
directed = TRUE
hyper = FALSE
loops = FALSE
multiple = FALSE
bipartite = FALSE
total edges= 5310
missing edges= 0
non-missing edges= 5310
Vertex attribute names:
color degree membership vertex.names
Edge attribute names not shown
g
node
"membership" occurs with the following frequency:
> table(g %v% "membership")
1 2 3 4 5
19 44 11 196 596
When I use the excellent ggnet2
package and the following function, a plot without a legend returns, although the documentation suggests a plot for node size, color, etc. is automatically generated (see the node legends section):
ggnet2(g_new, color = "membership", size = "degree") +
guides(size = F)
My guess is that you are passing a numeric vertex attribute to ggnet2
, which then understands it as a vector of color values.
Short answer:
Turn your membership
attribute into a character
string, and you will be fine.
Long answer:
Compare the two graphs in the example below to get the difference:
library(GGally)
library(ggplot2)
library(network)
library(sna)
g <- network(rgraph(10))
g %v% "membership" <- sample(1:5, 10, replace = TRUE)
g %v% "membership_string" <- as.character(g %v% "membership")
g %v% "degree" <- degree(g)
g
table(g %v% "membership")
## Your graph
ggnet2(g, color = "membership", size = "degree") +
guides(size = FALSE)
## Your graph, with the membership variable as a string
ggnet2(g, color = "membership_string", size = "degree") +
guides(size = FALSE)
If you want distinguishable colors instead of grayscale levels in your plot, you probably want something like this:
ggnet2(g, color = "membership_string", size = "degree", color.palette = "Set1") +
guides(size = FALSE)
Also, may I recommend that you give a try to the ggnetwork
package, which has additional functionalities?