Developers Club geek daily blog

1 year, 2 months ago
In the first part:
  • visualization of networks: what for? how?
  • visualization parameters
  • best practices — an esthetics and performance
  • formats of data and preparation
  • the description of data sets which are used in examples
  • beginning of work with igraph

In the second part: colors and fonts in diagrams R.

In the third part: parameters of graphs, tops and edges.

In the fourth part: placements of a network.

In the fifth part: emphasis of properties of a network, tops, edges, ways.

In the sixth part: interactive visualization of networks, other methods of representation of a network.

In this part: the animated visualization of networks, evolution of a network in time.

The interactive and animated visualization of a network


Interactive three-dimensional networks in R


Now it is easier and easier to export diagrams R to html/javascript. There are many libraries, such as rcharts and htmlwidgets, which will be useful during creation of web diagrams directly from R. We will look at networkD3 library which, apparently from the name, creates interactive visualization of networks by means of javascript of D3 library.

It is necessary to understand that the visualization created with the help networkD3, are most useful as a starting point to further work. If you know javascript a little, it is possible to use them as the first step and to change before receipt of desirable result.

If you have no library networkD3, set it:
install.packages("networkD3")

Data which uses this library — the standard list of edges with couple of little changes. In order that everything earned, it is necessary that identifiers of tops were numerical and started from scratch. The easy method to achieve they are to turn our alphabetic identifiers into a factor variable, the received result — in number, and to provide numbering from scratch with subtraction of unit.
library(networkD3)

el <- data.frame(from=as.numeric(factor(links$from))-1, 
                 to=as.numeric(factor(links$to))-1 )

Tops have to be in the same order, as a column - "source" in communications:
nl <- cbind(idn=factor(nodes$media, levels=nodes$media), nodes) 

Now it is possible to create interactive representation. Parameter Group it is used for coloring of tops. Nodesize — it is not the size of top as it would be possible to think, and number of a column in data on tops which needs to be used for a size task. Parameter charge manages pushing away (less than zero) or an attraction (more than zero).
forceNetwork(Links = el, Nodes = nl, Source="from", Target="to",
               NodeID = "idn", Group = "type.label",linkWidth = 1,
               linkColour = "#afafaf", fontSize=12, zoom=T, legend=T,
               Nodesize=6, opacity = 0.8, charge=-300, 
               width = 600, height = 400)

Visualization of static and dynamic networks on R, part 7, the last

Simple animation of diagrams in R


If you already set ndtv, you also have to have animation packet. If is not present, now it is a high time to set it — install.packages('animation'). Pay attention, this packet allows to create without effort different (not necessarily belonging to networks) animations in R. It works so: several diagrams which integrate then in GIF are created.

Dirty trick here following: that it earned, not only the packet of R, but also the special ImageMagick program is necessary.
library(animation) 
library(igraph)

ani.options("convert") # Убедитесь, что пакет знает, где находится ImageMagick
# Если не находит, укажите правильный путь в вашей системе.
ani.options(convert="C:/Program Files/ImageMagick-6.8.8-Q16/convert.exe") 

Now we will create 4 diagrams of a network (the same, as earlier), only this time in command saveGIF. The interval of animation is established by parameter interval, parameter movie.name sets the name of the gif-file.
l <- layout.fruchterman.reingold(net)

saveGIF( {  col <- rep("grey40", vcount(net))
            plot(net, vertex.color=col, layout=l)
            
            step.1 <- V(net)[media=="Wall Street Journal"]
            col[step.1] <- "#ff5100"
            plot(net, vertex.color=col, layout=l)
            
            step.2 <- unlist(neighborhood(net, 1, step.1, mode="out"))
            col[setdiff(step.2, step.1)] <- "#ff9d00"
            plot(net, vertex.color=col, layout=l) 
            
            step.3 <- unlist(neighborhood(net, 2, step.1, mode="out"))
            col[setdiff(step.3, step.2)] <- "#FFDD1F"
            plot(net, vertex.color=col, layout=l)  },
          interval = .8, movie.name="network_animation.gif" )
 
 detach(package:igraph)
 detach(package:animation
Visualization of static and dynamic networks on R, part 7, the last

Interactive networks with ndtv-d3


Interactive diagrams of static networks

In this section we will create more difficult visualization with a packet ndtv. It is not necessary for creation of animations additional for software. If you want to save animations as video files (look ?saveVideo), you need the FFmpeg video converter. To learn what installer is suitable for your OS, execute ?install.ffmpeg. To use all available arrangements, you also need Java.
install.packages("ndtv", dependencies=T)

As this packet is part of Statnet, it will accept objects from a packet network, as what we created earlier.
library(ndtv)
net3 

The majority of parameters have intuitively clear names (bg — background color of the diagram). Two new parameters which were not used earlier — vertex.tooltip and edge.tooltip. They contain information which can be seen, having guided the mouse cursor at a network element. Pay attention, parameters for tooltip balloons accept the html tags — for example, we use a line break tag — <br>. Parameter launchBrowser specifies R to open the turned-out file with visualization (filename) in the browser.
render.d3movie(net3, usearrows = F, displaylabels = F, bg="#111111", 
       vertex.border="#ffffff", vertex.col =  net3 %v% "col",
       vertex.cex = (net3 %v% "audience.size")/8, 
       edge.lwd = (net3 %e% "weight")/3, edge.col = '#55555599',
       vertex.tooltip = paste("<b>Name:</b>", (net3 %v% 'media') , "<br>",
                              "<b>Type:</b>", (net3 %v% 'type.label')),
       edge.tooltip = paste("<b>Edge type:</b>", (net3 %e% 'type'), "<br>", 
                            "<b>Edge weight:</b>", (net3 %e% "weight" ) ),
       launchBrowser=F, filename="Media-Network.html", output.mode='inline') 

Visualization of static and dynamic networks on R, part 7, the last

Animation of evolution of a network

The animated visualization — a good method to show evolution in time small or the average size of a network. At the moment, ndtv — the best packet of R intended for this purpose — especially after recently the feature for three-dimensional visualization was added.

To work with animation of a network in ndtv, it is necessary to understand the dynamic format of the Statnet network implemented in a packet networkDynamic. Let's look at one of data sets included in a packet as an example:
data(short.stergm.sim)
short.stergm.sim 
head(as.data.frame(short.stergm.sim))

##   onset terminus tail head onset.censored
## 1     0        1    3    5          FALSE
## 2    10       20    3    5          FALSE
## 3     0       25    3    6          FALSE
## 4     0        1    3    9          FALSE
## 5     2       25    3    9          FALSE
## 6     0        4    3   11          FALSE

##   terminus.censored duration edge.id
## 1             FALSE        1       1
## 2             FALSE       10       1
## 3             FALSE       25       2
## 4             FALSE        1       3
## 5             FALSE       23       3
## 6             FALSE        4       4

Here we see the list of edges. Each edge proceeds from top which identifier is in a column tail, also enters top with the identifier in a column head. The edge exists from a time mark onset to a time mark terminus. Onset and terminus marked with censored mean the beginning and the end of supervision over a network, but not the actual formation and disappearance of communications.

It is possible to build easily a network, not in view of its temporary component (having integrated everything ever the provided tops and edges):
plot(short.stergm.sim) 

Visualization of static and dynamic networks on R, part 7, the last

Let's build a network in a timepoint 1:
plot( network.extract(short.stergm.sim, at=1) )

Visualization of static and dynamic networks on R, part 7, the last

Let's construct tops and edges, active with first on the fifth timepoint:
plot( network.extract(short.stergm.sim, onset=1, terminus=5, rule="all") )

Visualization of static and dynamic networks on R, part 7, the last

Let's construct tops and edges, active with first on the tenth timepoint:
plot( network.extract(short.stergm.sim, onset=1, terminus=10, rule="any") ) 

Visualization of static and dynamic networks on R, part 7, the last

Let's make short three-dimensional animation of a network of an example:
render.d3movie(short.stergm.sim,displaylabels=TRUE) 

Now we are ready to create and animate an own dynamic network. The object-dynamic network can be received in several ways: from a set of the networks / matrixes representing different timepoints of matrixes / data sets with lists of tops and edges where it is specified when they are active or when change a status. More information is available in ?networkDynamic.

Let's add a time component to our example with mass media. The code lower takes a time interval from 0 to 50 and all this time does active network tops. Edges appear one behind another, everyone is active from the moment of emergence to the 50th timepoint. Let's create such network with the help networkDynamic, time for tops — node.spelss, for edges — edge.spells.
vs <- data.frame(onset=0, terminus=50, vertex.id=1:17)
es <- data.frame(onset=1:49, terminus=50, 
                 head=as.matrix(net3, matrix.type="edgelist")[,1],
                 tail=as.matrix(net3, matrix.type="edgelist")[,2])

net3.dyn <- networkDynamic(base.net=net3, edge.spells=es, vertex.spells=vs)

If just to try to construct a networkDynamic-network, the combined network for the entire period of supervision, i.e. an initial example with mass media will turn out.
plot(net3.dyn, vertex.cex=(net3 %v% "audience.size")/7, vertex.col="col")

One of methods to show evolution of a network in time — static pictures for different timepoints. Though it is possible to generate them on one as we did higher, ndtv offers easier method. Command for this purpose — filmstrip. As well as in function par(), managing director of parameters of diagrams R, here mfrow sets quantity of lines and columns in the table on several diagrams.
filmstrip(net3.dyn, displaylabels=F, mfrow=c(1, 5),
          slice.par=list(start=0, end=49, interval=10, 
                         aggregate.dur=10, rule='any'))
Visualization of static and dynamic networks on R, part 7, the last

It is possible to calculate animation coordinates in advance (otherwise they are considered at the time of animation creation). Here animation.mode — algorithm of an arrangement — one of "kamadakawai", "MDSJ", "Graphviz" and "useAttribute" (the coordinate set by the user).
compute.animation(net3.dyn, animation.mode = "kamadakawai",
                  slice.par=list(start=0, end=50, interval=1, 
                         aggregate.dur=1, rule='any'))

render.d3movie(net3.dyn, usearrows = F, 
       displaylabels = F, label=net3 %v% "media",
       bg="#ffffff", vertex.border="#333333",
       vertex.cex = degree(net3)/2,  
       vertex.col = net3.dyn %v% "col",
       edge.lwd = (net3.dyn %e% "weight")/3, 
       edge.col = '#55555599',
       vertex.tooltip = paste("<b>Name:</b>", (net3.dyn %v% "media") , "<br>",
                              "<b>Type:</b>", (net3.dyn %v% "type.label")),
       edge.tooltip = paste("<b>Edge type:</b>", (net3.dyn %e% "type"), "<br>", 
                            "<b>Edge weight:</b>", (net3.dyn %e% "weight" ) ),
       launchBrowser=T, filename="Media-Network-Dynamic.html",
       render.par=list(tween.frames = 30, show.time = F),
       plot.par=list(mar=c(0,0,0,0)), output.mode='inline' )

Visualization of static and dynamic networks on R, part 7, the last

In addition to dynamic tops and edges of ndtv accepts dynamic parameters. It was possible to add them to data sets of es and vs above. Moreover, function of creation can apply special parameters and create dynamic arguments directly in process. For example, function(slice) { some calculations from slice } will make actions in the current temporary cut, allowing to change parameters thereby dynamically. Pay attention to the size of tops below:
compute.animation(net3.dyn, animation.mode = "kamadakawai",
                  slice.par=list(start=0, end=50, interval=4, 
                         aggregate.dur=1, rule='any'))

render.d3movie(net3.dyn, usearrows = F, 
       displaylabels = F, label=net3 %v% "media",
       bg="#000000", vertex.border="#dddddd",
       vertex.cex = function(slice){ degree(slice)/2.5 },  
       vertex.col = net3.dyn %v% "col",
       edge.lwd = (net3.dyn %e% "weight")/3, 
       edge.col = '#55555599', 
       vertex.tooltip = paste("<b>Name:</b>", (net3.dyn %v% "media") , "<br>",
                              "<b>Type:</b>", (net3.dyn %v% "type.label")),
       edge.tooltip = paste("<b>Edge type:</b>", (net3.dyn %e% "type"), "<br>", 
                            "<b>Edge weight:</b>", (net3.dyn %e% "weight" ) ),
       launchBrowser=T, filename="Media-Network-even-more-Dynamic.html",
       render.par=list(tween.frames = 15, show.time = F), output.mode='inline')

Visualization of static and dynamic networks on R, part 7, the last

This article is a translation of the original post at habrahabr.ru/post/268979/
If you have any questions regarding the material covered in the article above, please, contact the original author of the post.
If you have any complaints about this article or you want this article to be deleted, please, drop an email here: sysmagazine.com@gmail.com.

We believe that the knowledge, which is available at the most popular Russian IT blog habrahabr.ru, should be accessed by everyone, even though it is poorly translated.
Shared knowledge makes the world better.
Best wishes.

comments powered by Disqus