Skip to content

Instantly share code, notes, and snippets.

@briatte
Last active December 26, 2015 21:09
Show Gist options
  • Save briatte/7214253 to your computer and use it in GitHub Desktop.
Save briatte/7214253 to your computer and use it in GitHub Desktop.
R Addicts 2013 ggnet demo code

See demo code below and companion slides for details.

The demo code will install the required packages and download one-mode example network data from the ggnet repository. For two-mode example network data, see the neta repository. Both represent ties between French Members of Parliament from recent legislatures. For more data, see NosDéputés.fr.

ggnet example plot

## SLIDE 1. PACKAGES
load.package = function(..., mute = TRUE) {
sapply(c(...), function(x) {
if(!require(x, quietly = mute, character.only = TRUE))
install.packages(x, quiet = mute)
library(x, character.only = TRUE, quietly = mute)
})
}
# packages: viz
load.package("GGally", "RColorBrewer")
# packages: networks
load.package("intergraph", "sna")
## SLIDE 2. DATA
read.tsv = function(x, url = "https://raw.github.com/briatte/ggnet/master/") {
if(!require(downloader)) install.packages("downloader")
if(!file.exists(x)) downloader::download(paste0(url, x), x, mode = "wb")
return(read.csv(x, sep = "\t"))
}
# data: MPs
ids = read.tsv("nodes.tsv")
names(ids)
# data: Twitter
df = read.tsv("network.tsv")
names(df)
## SLIDE 3. PLOT
# build: network
net = network::network(df)
mps = data.frame(Twitter = network::network.vertex.names(net))
# build: colours
mp.groups = merge(mps, ids, by = "Twitter")$Groupe
mp.colors = RColorBrewer::brewer.pal(9, "Set1")[c(3, 1, 9, 6, 8, 5, 2)]
# plot: network
ggnet(net,
weight = "degree", # inlinks + outlinks
quantize = TRUE, # weight by quartile
node.group = mp.groups, # assign node groups
node.color = mp.colors) # assign node colors
# kthxbye
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment