if (!require("igraph")) install.packages("igraph", repos="https://cran.cnr.berkeley.edu/", dependencies = TRUE)

library("igraph")  # load the required library
# DATASET edgelist
setwd(working_path)
nodes <- read.csv("Dataset1-Media-Example-NODES.csv", header=T, as.is=T)
links <- read.csv("Dataset1-Media-Example-EDGES.csv", header=T, as.is=T)

# What the nodes file look like BEFORE aggregation
head(nodes) 
##    id               media media.type type.label audience.size
## 1 s01            NY Times          1  Newspaper            20
## 2 s02     Washington Post          1  Newspaper            25
## 3 s03 Wall Street Journal          1  Newspaper            30
## 4 s04           USA Today          1  Newspaper            32
## 5 s05            LA Times          1  Newspaper            20
## 6 s06       New York Post          1  Newspaper            50
# What the links file look like BEFORE aggregation
head(links) 
##   from  to weight      type
## 1  s01 s02     10 hyperlink
## 2  s01 s02     12 hyperlink
## 3  s01 s03     22 hyperlink
## 4  s01 s04     21 hyperlink
## 5  s04 s11     22   mention
## 6  s05 s15     21   mention
links <- aggregate(weight ~ from + to + type, data = links, sum)
links <- links[order(links$from, links$to),] # Sort by from and to

# What the links file look like AFTER aggregation
head(links) 
##    from  to      type weight
## 4   s01 s02 hyperlink     22
## 6   s01 s03 hyperlink     22
## 11  s01 s04 hyperlink     21
## 44  s01 s15   mention     20
## 1   s02 s01 hyperlink     23
## 7   s02 s03 hyperlink     21
# Import edgelist
net <- graph.data.frame(links, nodes, directed=T)
net # showing what net looks like
## IGRAPH 6bf0a9a DNW- 17 49 -- 
## + attr: name (v/c), media (v/c), media.type (v/n), type.label
## | (v/c), audience.size (v/n), type (e/c), weight (e/n)
## + edges from 6bf0a9a (vertex names):
##  [1] s01->s02 s01->s03 s01->s04 s01->s15 s02->s01 s02->s03 s02->s09
##  [8] s02->s10 s03->s01 s03->s04 s03->s05 s03->s08 s03->s10 s03->s11
## [15] s03->s12 s04->s03 s04->s06 s04->s11 s04->s12 s04->s17 s05->s01
## [22] s05->s02 s05->s09 s05->s15 s06->s06 s06->s16 s06->s17 s07->s03
## [29] s07->s08 s07->s10 s07->s14 s08->s03 s08->s07 s08->s09 s09->s10
## [36] s10->s03 s12->s06 s12->s13 s12->s14 s13->s12 s13->s17 s14->s11
## [43] s14->s13 s15->s01 s15->s04 s15->s06 s16->s06 s16->s17 s17->s04
V(net)$name <- V(net)$media

## Showing 
degree(net,mode = c("all"))
##            NY Times     Washington Post Wall Street Journal 
##                   8                   6                  13 
##           USA Today            LA Times       New York Post 
##                   9                   5                   8 
##                 CNN               MSNBC            FOX News 
##                   5                   5                   4 
##                 ABC                 BBC          Yahoo News 
##                   5                   3                   6 
##         Google News         Reuters.com         NYTimes.com 
##                   4                   4                   5 
##  WashingtonPost.com             AOL.com 
##                   3                   5
betweenness(net)
##            NY Times     Washington Post Wall Street Journal 
##           17.666667            1.000000          144.500000 
##           USA Today            LA Times       New York Post 
##           97.000000           50.000000           21.500000 
##                 CNN               MSNBC            FOX News 
##            0.500000           14.000000            1.000000 
##                 ABC                 BBC          Yahoo News 
##           29.000000            0.000000           41.500000 
##         Google News         Reuters.com         NYTimes.com 
##           21.500000            1.000000            4.666667 
##  WashingtonPost.com             AOL.com 
##            0.000000           66.000000
## igraph plot
plot(net,vertex.size=10, edge.arrow.size=.2, edge.curved=0,vertex.color='orange', vertex.frame.color='#555555', vertex.label.color='blue',vertex.label.cex=.7)

## igraph plot with node color
plot(net,vertex.size=10, edge.arrow.size=.2, edge.curved=0,vertex.color='pink', vertex.frame.color='#555555', vertex.label.color='blue',vertex.label.cex=.7)

## igraph plot with various size
plot(net,vertex.size=V(net)$audience.size, edge.arrow.size=.2, edge.curved=0,vertex.color='orange', vertex.frame.color='#555555', vertex.label.color='blue',vertex.label.cex=.7)

## igraph plot with specific layout 
# Random layout
plot(net,layout=layout.random, vertex.size=V(net)$audience.size,edge.arrow.size=.2, edge.curved=0,vertex.color='orange', vertex.frame.color='#555555', vertex.label.color='blue',vertex.label.cex=.7)

L_fr <- layout_with_fr(net) # Fruchterman-Reingold layout algorithm
head(L_fr) 
##            [,1]        [,2]
## [1,] 1.42125506  0.04396139
## [2,] 1.79047344 -0.11648445
## [3,] 1.65538465  0.36987635
## [4,] 1.18493263  0.59282030
## [5,] 1.59078261 -0.52771621
## [6,] 0.03966739  0.59301819
plot(net,vertex.size=V(net)$audience.size,layout=L_fr,edge.arrow.size=.2, edge.curved=0,vertex.color='orange', vertex.frame.color='#555555', vertex.label.color='blue',vertex.label.cex=.7)

## Change background color
par(bg = 'black')
plot(net,vertex.size=V(net)$audience.size,layout=L_fr,edge.arrow.size=.2, edge.curved=0,vertex.color='orange', vertex.frame.color='#555555', vertex.label.color='white',vertex.label.cex=.7)

## No fixed aspect ratio
par(bg = 'black')
plot(net,vertex.size=V(net)$audience.size,layout=L_fr,edge.arrow.size=.2, edge.curved=0,vertex.color='orange', vertex.frame.color='#555555', vertex.label.color='white',vertex.label.cex=.7,asp=0)

wc <- walktrap.community(net)
dendPlot(wc, mode="hclust")  # Create a dendrogram

plot(wc, net, vertex.size=5, vertex.label.cex=.7, edge.arrow.size=.2, edge.curved=0)

membership(wc)
##            NY Times     Washington Post Wall Street Journal 
##                   1                   1                   1 
##           USA Today            LA Times       New York Post 
##                   1                   1                   3 
##                 CNN               MSNBC            FOX News 
##                   2                   2                   2 
##                 ABC                 BBC          Yahoo News 
##                   2                   1                   4 
##         Google News         Reuters.com         NYTimes.com 
##                   4                   4                   1 
##  WashingtonPost.com             AOL.com 
##                   3                   3
V(net)$grp_member <- membership(wc)
## Plotly
if (!require("plotly")) install.packages("plotly", repos="https://cran.cnr.berkeley.edu/", dependencies = TRUE)
library(plotly)
Xn <- L_fr[,1]
Yn <- L_fr[,2]
es <- as.data.frame(get.edgelist(net))

edge_shapes <- list()  # Prepare a empty list

for(i in 1:length(E(net))) {
  v0 <- es[i,]$V1
  v1 <- es[i,]$V2
  
  edge_shape <- list(
    type = "line",
    line = list(color = "#030303", width = 0.3),
    x0 = Xn[v0],
    y0 = Yn[v0],
    x1 = Xn[v1],
    y1 = Yn[v1]
  )
  
  edge_shapes[[i]] <- edge_shape
}

a <- list(  
  showarrow=TRUE,
  arrowhead=3,
  arrowsize=1,
  arrowwidth=1.5,
  arrowcolor='#636363'
)

network <- plot_ly()

network <- add_markers(network, x = ~Xn, y = ~Yn, color = V(net)$grp_member, mode = "markers", marker = list(size = V(net)$audience.size, annotations = a), text = V(net)$name, hoverinfo = "text")

axis <- list(title = "", showgrid = FALSE, showticklabels = FALSE, zeroline = FALSE) # Don't display axis and tick labels

p <- layout(network,
  title = 'Media Network in Plotly',
  shapes = edge_shapes,
  xaxis = axis,
  yaxis = axis
)

p <- hide_colorbar(p) # Don't display color bar

p
## Network Visualization using D3
if (!require("networkD3")) install.packages("networkD3", repos="https://cran.cnr.berkeley.edu/", dependencies = TRUE)
library(networkD3)
edgeList <- get.data.frame(net,"edges")
nodeList <- get.data.frame(net,"vertices")

edgeList$SourceID <- match(edgeList$from, nodeList$name)-1
edgeList$TargetID <- match(edgeList$to, nodeList$name)-1

D3_network <- networkD3::forceNetwork(
  Links = edgeList, # data frame that contains info about edges
  Nodes = nodeList, # data frame that contains info about nodes
  Source = "SourceID", # ID of source node 
  Target = "TargetID", # ID of target node
  NodeID = "name", # display value from the node list (e.g., node name)
  Group = "grp_member",  # value we want to use for node color
  Value = "weight",
  Nodesize = "audience.size",  # node size according to audience size
  charge = -500,
  height = 500, # Size of the plot (vertical)
  width = 1000,  # Size of the plot (horizontal)
  fontSize = 50, # Font size
  linkWidth = 1, # Link width
  zoom = TRUE # ability to zoom when click on the node
) 

# Plot network
D3_network 
# Rescaling the node size
nsize_max <- max(nodeList$audience.size)
nsize_min <- min(nodeList$audience.size)
max_size <- 500

nodeList$audience.size1 <- max_size*(nodeList$audience.size-nsize_min)/(nsize_max-nsize_min)

D3_network <- networkD3::forceNetwork(
  Links = edgeList, # data frame that contains info about edges
  Nodes = nodeList, # data frame that contains info about nodes
  Source = "SourceID", # ID of source node 
  Target = "TargetID", # ID of target node
  NodeID = "name", # display value from the node list (e.g., node name)
  Group = "grp_member",  # value we want to use for node color
  Value = "weight",
  Nodesize = "audience.size1",  # node size according to audience size
  charge = -500,
  height = 500, # Size of the plot (vertical)
  width = 1000,  # Size of the plot (horizontal)
  fontSize = 50, # Font size
  linkWidth = 1, # Link width
  zoom = TRUE # ability to zoom when click on the node
) 

D3_network
# Save your work in html 
#networkD3::saveNetwork(D3_network_LM, "D3_LM.html", selfcontained = TRUE)