Skip to content

Instantly share code, notes, and snippets.

@olp-cs
Last active April 30, 2016 18:31
Show Gist options
  • Save olp-cs/3c56418533d0d39176356dc8b64239d3 to your computer and use it in GitHub Desktop.
Save olp-cs/3c56418533d0d39176356dc8b64239d3 to your computer and use it in GitHub Desktop.
library(igraph) # to work with graphs
library(RColorBrewer) # to use a color palette
library(plotrix) # to rescale variables
# Read the data
raw_data <- read.csv("network_data.csv")
names(raw_data) <- c("Source", "Target", "Count", "Money")
# reformat data for igraph library
# mark source and target vertices -> different "type"
vertices.source <- data.frame(unique(raw_data$Source))
vertices.target <- data.frame(unique(raw_data$Target))
vertices.source$type = TRUE
vertices.target$type = FALSE
names(vertices.source) <- c("name", "type")
names(vertices.target) <- c("name", "type")
vertices.target$name <- as.character(vertices.target$name)
vertices <- rbind(vertices.source, vertices.target)
# create a bipartite graph
g <- graph.data.frame(raw_data, directed=FALSE, vertices=vertices)
# define color and shape mappings
col <- c("steelblue", "orange")
shape <- c("circle", "square")
# set edge width depending on the deal amount
# - tune it, so that the differences would be visible on screen
E(g)$width <- log(E(g)$Money) - min(log(E(g)$Money)) + 1
# set edge color and shape depending on the type: source or target?
V(g)$color = col[as.numeric(V(g)$type) + 1]
V(g)$shape = shape[as.numeric(V(g)$type) + 1]
# choose a color palette - this one is a 9-color palette called "YlOrRd"
palette <- brewer.pal( 9, "YlOrRd" )
plot(g,
# tune how node labels are displayed
vertex.label.cex=.7,
# set edge color in a way that it would be visible
edge.color = palette [ rescale ( log(E(g)$Count), range(4, 9) ) ]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment