---
title: "Practical 3"
author: "James Hollway"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Practical 3}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

# Packages for plotting

There are a host of packages for plotting in R, and for plotting networks in R.
Plotting in R is typically based around two main approaches:
the 'base' approach in R by default,
and the 'grid' approach made popular by the famous and very flexible `{ggplot2}` package.^['gg' stands for the Grammar of Graphics.]
Approaches to plotting _graphs_ or _networks_ in R can be similarly divided.
The two classic packages are `{igraph}` and `{sna}`, both building upon the base R graphics engine,
but newer packages [`{ggnetwork}`](https://www.r-bloggers.com/2016/03/ggnetwork-network-geometries-for-ggplot2/) and 
[`{ggraph}`](https://ggraph.data-imaginist.com/index.html) build upon a grid approach.^[
Others include: 'Networkly' for creating 2-D and 3-D interactive networks
that can be rendered with plotly and can be easily integrated into
shiny apps or markdown documents;
'visNetwork' interacts with javascript (vis.js) to make interactive networks
(http://datastorm-open.github.io/visNetwork/); and
'networkD3' interacts with javascript (D3) to make interactive networks
(https://www.r-bloggers.com/2016/10/network-visualization-part-6-d3-and-r-networkd3/).
]
`{migraph}` builds upon the ggplot2/ggraph engine for plotting.

```{r setup}
library(migraph)
brandes
autographr(brandes)
```

For this exercise, we'll use the `brandes` dataset.
This dataset is in a 'tidygraph' format, 
but migraph makes it easy to coerce this into other forms
to be compatible with other packages.

```{r coercion}
as_igraph(brandes)
as_network(brandes)
mat <- as_matrix(brandes)
```

# Calculating different centrality measures

Let's start with calculating degree, as it is easy to calculate yourself.
Just sum the rows or columns of the matrix!

```{r degreesum}
(degrees <- rowSums(mat))
rowSums(mat) == colSums(mat)
# Are they all equal? Why?
# You can also just use a built in command in migraph though:
node_degree(brandes)
```

Often we are interested in the distribution of (degree) centrality in a network.
`{migraph}` offers a way to get a pretty good first look at this distribution,
though there are more elaborate ways to do this in base and grid graphics.

```{r distrib}
ggdistrib(brandes, node_degree)
```

Other measures of centrality can be a little trickier to calculate by hand.
Fortunately, we can use functions from migraph to help:

```{r micent}
node_betweenness(brandes)
node_closeness(brandes)
node_eigenvector(brandes)
# TASK: Can you create degree distributions for each of these?
```

Note that there are an enormous number of centrality measures available
in R across a range of packages.
In addition to the main four used here, `{igraph}` includes:

```
graph.strength()
alpha_centrality()
power_centrality()
page_rank()
eccentricity()
hub_score()
authority_score()
subgraph_centrality()
```

`{sna}` implements most of these too, plus a few extra:

```
flowbet()
loadcent()
gilschmidt()
infocent()
stresscent()
```

There are also some dedicated centrality packages,
such as [centiserve](https://www.centiserver.org/),
CINNA, influenceR, and keyplayer.
There are also pretty exhaustive [discussions of this online](https://www.r-bloggers.com/2018/12/network-centrality-in-r-an-introduction/).

# Plotting different centrality measures

There is also a function in `{migraph}` that
plots our network and highlights the node with the maximum (e.g. degree) score.
This is basically doing the same as what was in the original script,
just gives you the function to do this:

```{r ggid}
ggidentify(brandes, node_degree)
ggidentify(brandes, node_betweenness)
ggidentify(brandes, node_closeness)
ggidentify(brandes, node_eigenvector)
```

How neat!

# Calculating centralization

`{migraph}` also implements centralization functions.
Here we are no longer interested in the level of the node,
but in the level of the whole graph, so the syntax is:

```{r centzn}
graph_degree(brandes)
graph_betweenness(brandes)
graph_closeness(brandes)
graph_eigenvector(brandes) # note that graph_eigenvector() is not yet implemented for two-mode networks
graph_eigenvector(brandes, digits = 4)
graph_eigenvector(brandes, digits = FALSE)
```

By default, these scores are rounded to 2 decimal places,
but you can alter or turn this off.

# Exporting plots to PDF

We can print the plots we have made to PDF by point-and-click
by selecting 'Save as PDF...' from under the 'Export' dropdown menu
in the plots panel tab of RStudio.

If you want to do this programmatically,
say because you want to record how you have saved it so that you can
e.g. make some changes to the parameters at some point,
this is also not too difficult.

After running the (gg-based) plot you want to save,
use the command `ggsave("my_filename.pdf")` to save your plot
as a PDF to your working directory.
If you want to save it somewhere else, you will need to specify the file path
(or change the working directory, but that might be more cumbersome).
If you want to save it as a different filetype,
replace `.pdf` with e.g. `.png` or `.jpeg`.
See `?ggsave` for more.

But what if we want to have a single image/figure with multiple plots?
This can be a little tricky with gg-based plots,
but fortunately the 'gridExtra' package is here to help.

```{r multiplot}
gd <- ggidentify(brandes, node_degree) + 
  ggtitle("Degree", subtitle = graph_degree(brandes))
gc <- ggidentify(brandes, node_closeness) + 
  ggtitle("Closeness", subtitle = round(graph_closeness(brandes), 2))
gb <- ggidentify(brandes, node_betweenness) + 
  ggtitle("Betweenness", subtitle = round(graph_betweenness(brandes), 2))
ge <- ggidentify(brandes, node_eigenvector) + 
  ggtitle("Eigenvector")
grid.arrange(gd, gb, gc, ge, ncol = 2)
# ggsave("brandes-centralities.pdf")
```

# Tasks

1. Import the drugnet data from Moodle
(Since it is an RData file, you can just load it).
`load("drugnet.RData")`

2. Name a plausible research question you could ask of this data
for each of the four main centrality measures
(degree, betweenness, closeness, eigenvector)
You may want to add these as titles or subtitles to each plot.

3. How centralized is the network?
