Tarak
Tarak

Reputation: 1075

Plot a simple network graph in R

I have a data frame as

mydf <- data.frame(ID = c(1,2,3,4,5), MatchedID = c(3,4,2,5,1), Weight = c(12,45,5,19,9))

I wish to plot a network graph showing relation between ID and matchedID and weights as strength of that relationship. What is the best way to represent this with labels? I like the ones at https://briatte.github.io/ggnet/

Upvotes: 0

Views: 1134

Answers (1)

Roman
Roman

Reputation: 17668

You can try:

library(igraph)
g <- graph_from_data_frame(mydf, directed=TRUE)
g <- set_edge_attr(g, "weight", value = mydf$Weight)
plot(g, edge.width = E(g)$weight/5, edge.label=E(g)$weight)

enter image description here

Or use ggplot2

library(GGally)
library(sna)
library(network)
library(tidyverse)

mydf %>% 
    spread(MatchedID, Weight, fill = 0) %>%  
    select(-ID) %>%
    network(names.eval = "weights", ignore.eval = FALSE) %>% 
    ggnet2(label = TRUE, edge.label = "weights")

enter image description here

Upvotes: 3

Related Questions