{"id":547,"date":"2012-11-05T15:18:33","date_gmt":"2012-11-05T15:18:33","guid":{"rendered":"http:\/\/rulesofreason.wordpress.com\/?p=547"},"modified":"2012-11-05T15:18:33","modified_gmt":"2012-11-05T15:18:33","slug":"network-visualization-in-r-with-the-igraph-package","status":"publish","type":"post","link":"http:\/\/re-design.dimiter.eu\/?p=547","title":{"rendered":"Network visualization in R with the igraph package"},"content":{"rendered":"<p>In <a href=\"http:\/\/re-design.dimiter.eu\/2012\/10\/23\/the-hidden-structure-of-academic-organizations\/\" target=\"_blank\">this<\/a> post I showed a visualization of the organizational network of my department. Since several people asked for details how the plot has been produced, I will provide the code and some extensions below. The plot has been done entirely in <code>R (2.14.01)<\/code> with the help of the <code>igraph<\/code> package. It is a great package but I found the documentation somewhat difficult to use, so hopefully this post can be a helpful introduction to network visualization with <code>R<\/code>. Here we go:<\/p>\n<pre># Load the igraph package (install if needed)\n\n<code>require(igraph)<\/code>\n\n# Data format. The data is in 'edges' format meaning that each row records a relationship (edge) between two people (vertices).\n# Additional attributes can be included. Here is an example:\n#\tSupervisor\tExaminer\tGrade\tSpec(ialization)\n#\tAA\t\tBD\t\t6\tX\t\n#\tBD\t\tCA\t\t8\tY\n#\tAA\t\tDE\t\t7\tY\n#\t...\t\t...\t\t...\t...\n# In this anonymized example, we have data on co-supervision with additional information about grades and specialization. \n# It is also possible to have the data in a matrix form (see the igraph documentation for details)\n\n# Load the data. The data needs to be loaded as a table first: \n\n<code>bsk&lt;-read.table(\"http:\/\/www.dimiter.eu\/Data_files\/edgesdata3.txt\", sep='t', dec=',', header=T)<\/code>#specify the path, separator(tab, comma, ...), decimal point symbol, etc.\n\n# Transform the table into the required graph format:\n<code>bsk.network&lt;-graph.data.frame(bsk, directed=F) <\/code>#the 'directed' attribute specifies whether the edges are directed\n# or equivelent irrespective of the position (1st vs 2nd column). For directed graphs use 'directed=T'\n\n# Inspect the data:\n\n<code>V(bsk.network)<\/code> #prints the list of vertices (people)\n<code>E(bsk.network)<\/code> #prints the list of edges (relationships)\n<code>degree(bsk.network)<\/code> #print the number of edges per vertex (relationships per people)\n\n# First try. We can plot the graph right away but the results will usually be unsatisfactory:\n<code>plot(bsk.network)<\/code><\/pre>\n<p>Here is the result:<br \/>\n<a href=\"https:\/\/i0.wp.com\/re-design.dimiter.eu\/wp-content\/uploads\/2012\/11\/network_try1.png\"><img data-attachment-id=\"554\" data-permalink=\"http:\/\/re-design.dimiter.eu\/?attachment_id=554\" data-orig-file=\"https:\/\/i0.wp.com\/re-design.dimiter.eu\/wp-content\/uploads\/2012\/11\/network_try1.png?fit=800%2C600\" data-orig-size=\"800,600\" data-comments-opened=\"1\" data-image-meta=\"{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}\" data-image-title=\"network_try1\" data-image-description=\"\" data-medium-file=\"https:\/\/i0.wp.com\/re-design.dimiter.eu\/wp-content\/uploads\/2012\/11\/network_try1.png?fit=300%2C225\" data-large-file=\"https:\/\/i0.wp.com\/re-design.dimiter.eu\/wp-content\/uploads\/2012\/11\/network_try1.png?fit=800%2C600\" loading=\"lazy\" class=\"alignnone size-full wp-image-554\" title=\"network_try1\" alt=\"\" src=\"https:\/\/i0.wp.com\/re-design.dimiter.eu\/wp-content\/uploads\/2012\/11\/network_try1.png?resize=584%2C438\" height=\"438\" width=\"584\" srcset=\"https:\/\/i0.wp.com\/re-design.dimiter.eu\/wp-content\/uploads\/2012\/11\/network_try1.png?w=800 800w, https:\/\/i0.wp.com\/re-design.dimiter.eu\/wp-content\/uploads\/2012\/11\/network_try1.png?resize=300%2C225 300w, https:\/\/i0.wp.com\/re-design.dimiter.eu\/wp-content\/uploads\/2012\/11\/network_try1.png?resize=768%2C576 768w\" sizes=\"(max-width: 584px) 100vw, 584px\" data-recalc-dims=\"1\" \/><\/a><\/p>\n<p>Not very informative indeed. Let&#8217;s go on:<\/p>\n<pre> \n#Subset the data. If we want to exclude people who are in the network only tangentially (participate in one or two relationships only)\n# we can exclude the by subsetting the graph on the basis of the 'degree':\n\n<code>bad.vs&lt;-V(bsk.network)[degree(bsk.network)&lt;3]<\/code> #identify those vertices part of less than three edges\n<code>bsk.network&lt;-delete.vertices(bsk.network, bad.vs)<\/code> #exclude them from the graph\n\n# Plot the data.Some details about the graph can be specified in advance.\n# For example we can separate some vertices (people) by color:\n\n<code>V(bsk.network)$color&lt;-ifelse(V(bsk.network)$name=='CA', 'blue', 'red')<\/code> #useful for highlighting certain people. Works by matching the name attribute of the vertex to the one specified in the 'ifelse' expression\n\n# We can also color the connecting edges differently depending on the 'grade': \n\n<code>E(bsk.network)$color&lt;-ifelse(E(bsk.network)$grade==9, \"red\", \"grey\")<\/code>\n\n# or depending on the different specialization ('spec'):\n\n<code>E(bsk.network)$color&lt;-ifelse(E(bsk.network)$spec=='X', \"red\", ifelse(E(bsk.network)$spec=='Y', \"blue\", \"grey\"))<\/code>\n\n# Note: the example uses nested ifelse expressions which is in general a bad idea but does the job in this case\n# Additional attributes like size can be further specified in an analogous manner, either in advance or when the plot function is called:\n\n<code>V(bsk.network)$size&lt;-degree(bsk.network)\/10<\/code>#here the size of the vertices is specified by the degree of the vertex, so that people supervising more have get proportionally bigger dots. Getting the right scale gets some playing around with the parameters of the scale function (from the 'base' package)\n\n# Note that if the same attribute is specified beforehand and inside the function, the former will be overridden.\n# And finally the plot itself:\n<code>par(mai=c(0,0,1,0))<\/code> \t\t\t#this specifies the size of the margins. the default settings leave too much free space on all sides (if no axes are printed)\n<code>plot(bsk.network,<\/code>\t\t\t\t#the graph to be plotted\n<code>layout=layout.fruchterman.reingold,<\/code>\t# the layout method. see the igraph documentation for details\n<code>main='Organizational network example',<\/code>\t#specifies the title\n<code>vertex.label.dist=0.5,<\/code>\t\t\t#puts the name labels slightly off the dots\n<code>vertex.frame.color='blue',<\/code> \t\t#the color of the border of the dots \n<code>vertex.label.color='black',<\/code>\t\t#the color of the name labels\n<code>vertex.label.font=2,<\/code>\t\t\t#the font of the name labels\n<code>vertex.label=V(bsk.network)$name,<\/code>\t\t#specifies the lables of the vertices. in this case the 'name' attribute is used\n<code>vertex.label.cex=1<\/code>\t\t\t#specifies the size of the font of the labels. can also be made to vary\n<code>)<\/code>\n\n# Save and export the plot. The plot can be copied as a metafile to the clipboard, or it can be saved as a pdf or png (and other formats).\n# For example, we can save it as a png:\n<code>png(filename=\"org_network.png\", height=800, width=600)<\/code> #call the png writer\n#run the plot\n<code>dev.off()<\/code> #dont forget to close the device\n#And that's the end for now.<\/pre>\n<p>Here is the result:<br \/>\n<a href=\"https:\/\/i2.wp.com\/re-design.dimiter.eu\/wp-content\/uploads\/2012\/11\/org_network2.png\"><img data-attachment-id=\"575\" data-permalink=\"http:\/\/re-design.dimiter.eu\/?attachment_id=575\" data-orig-file=\"https:\/\/i2.wp.com\/re-design.dimiter.eu\/wp-content\/uploads\/2012\/11\/org_network2.png?fit=762%2C912\" data-orig-size=\"762,912\" data-comments-opened=\"1\" data-image-meta=\"{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}\" data-image-title=\"org_network\" data-image-description=\"\" data-medium-file=\"https:\/\/i2.wp.com\/re-design.dimiter.eu\/wp-content\/uploads\/2012\/11\/org_network2.png?fit=251%2C300\" data-large-file=\"https:\/\/i2.wp.com\/re-design.dimiter.eu\/wp-content\/uploads\/2012\/11\/org_network2.png?fit=762%2C912\" loading=\"lazy\" class=\"alignnone size-full wp-image-575\" title=\"org_network\" alt=\"\" src=\"https:\/\/i2.wp.com\/re-design.dimiter.eu\/wp-content\/uploads\/2012\/11\/org_network2.png?resize=584%2C698\" height=\"698\" width=\"584\" srcset=\"https:\/\/i2.wp.com\/re-design.dimiter.eu\/wp-content\/uploads\/2012\/11\/org_network2.png?w=762 762w, https:\/\/i2.wp.com\/re-design.dimiter.eu\/wp-content\/uploads\/2012\/11\/org_network2.png?resize=251%2C300 251w\" sizes=\"(max-width: 584px) 100vw, 584px\" data-recalc-dims=\"1\" \/><\/a><\/p>\n<p>Still not perfect, but much more informative and\u00a0aesthetically\u00a0pleasing.<\/p>\n<p>Additional information can be found on this <a href=\"http:\/\/igraph.sourceforge.net\/igraphbook\/index.html\" target=\"_blank\">guide<\/a> to <code>igraph<\/code> which is in development, the examples <a href=\"http:\/\/igraph.sourceforge.net\/screenshots2.html#1\" target=\"_blank\">here<\/a>, and the official CRAN <a href=\"http:\/\/cran.r-project.org\/web\/packages\/igraph\/igraph.pdf\" target=\"_blank\">documentation<\/a> of the package. Especially useful is this <a href=\"http:\/\/igraph.sourceforge.net\/doc\/R\/plot.common.html\" target=\"_blank\">list<\/a> of the plot attributes that can be tweaked. The plots can also be adjusted\u00a0interactively\u00a0using the\u00a0<code>tkplot<\/code> function instead of <code>plot<\/code>, but the options for saving the resulting figure are limited.<\/p>\n<p>Have fun with your networks!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this post I showed a visualization of the organizational network of my department. Since several people asked for details how the plot has been produced, I will provide the code and some extensions below. The plot has been done entirely in R (2.14.01) with the help of the igraph package. It is a great package but I found the documentation somewhat difficult to use, so hopefully this post can be a helpful introduction to network visualization with R. Here we go: # Load the igraph package (install if needed) require(igraph) # Data format. The data is in &#8216;edges&#8217; format meaning that each row records a relationship (edge) between two people (vertices). # Additional attributes can be included. Here is an example: # Supervisor Examiner Grade Spec(ialization) # AA BD 6 X # BD CA 8 Y # AA DE 7 Y # &#8230; &#8230; &#8230; &#8230; # In this anonymized example, we have data on co-supervision with additional information about grades and specialization. # It is also possible to have the data in a matrix form (see the igraph documentation for details) # Load the data. The data needs to be loaded as a table first: bsk&lt;-read.table(&#8220;http:\/\/www.dimiter.eu\/Data_files\/edgesdata3.txt&#8221;, sep=&#8217;t&#8217;, dec=&#8217;,&#8217;, header=T)#specify the path, separator(tab, comma, &#8230;), decimal point symbol, etc. # Transform the table into the required graph format: bsk.network&lt;-graph.data.frame(bsk, directed=F) #the &#8216;directed&#8217; attribute specifies whether the edges are directed # or equivelent irrespective of the position (1st vs 2nd column). For directed graphs use &#8216;directed=T&#8217; # Inspect the data:&#8230;<\/p>\n<div class=\"more-link-wrapper\"><a class=\"more-link\" href=\"http:\/\/re-design.dimiter.eu\/?p=547\">Continue reading<span class=\"screen-reader-text\">Network visualization in R with the igraph package<\/span><\/a><\/div>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false},"categories":[11,30,39],"tags":[322,323,437,438,439,440,455,480,606,607,650],"jetpack_featured_media_url":"","jetpack_publicize_connections":[],"jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p7g3hj-8P","jetpack-related-posts":[{"id":531,"url":"http:\/\/re-design.dimiter.eu\/?p=531","url_meta":{"origin":547,"position":0},"title":"The hidden structure of (academic) organizations","date":"October 23, 2012","format":false,"excerpt":"All organizations have a 'deep' hidden structure based on the social interactions among its members which might or might not coincide with the official formal one. University departments are no exception - if anything, the informal alliances, affinities, and allegiances within academic departments are only too visible and salient. Network\u2026","rel":"","context":"In &quot;Network analysis&quot;","img":{"alt_text":"","src":"https:\/\/i0.wp.com\/re-design.dimiter.eu\/wp-content\/uploads\/2012\/10\/social-network-bsk1.jpg?resize=350%2C200","width":350,"height":200},"classes":[]},{"id":621,"url":"http:\/\/re-design.dimiter.eu\/?p=621","url_meta":{"origin":547,"position":1},"title":"Music Network Visualization","date":"December 11, 2012","format":false,"excerpt":"Note: probably of interest only to the intersection of the readers who are into niche music genres and those interested in network visualization. My music interests have always been rather, hmm..., eclectic. Somehow IDM, ambient, darkwave, triphop, acid jazz, bossa nova, qawali, Mali blues and other more or less obscure\u2026","rel":"","context":"In &quot;Data visualization&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":439,"url":"http:\/\/re-design.dimiter.eu\/?p=439","url_meta":{"origin":547,"position":2},"title":"New tool for discourse network analysis","date":"April 11, 2012","format":false,"excerpt":"EJPR has just published an article introducing a new tool for 'discourse network analysis'. Using the tool, you can measure and visualize political discourses and the networks of actors affiliated to each discourse. One can study the actor congruence networks (based on the number of statements actors share), concept congruence\u2026","rel":"","context":"In &quot;Data visualization&quot;","img":{"alt_text":"","src":"https:\/\/i0.wp.com\/re-design.dimiter.eu\/wp-content\/uploads\/2012\/04\/discourse-network.jpg?resize=350%2C200","width":350,"height":200},"classes":[]},{"id":496,"url":"http:\/\/re-design.dimiter.eu\/?p=496","url_meta":{"origin":547,"position":3},"title":"Scatterplots vs. regression tables (Economics professors edition)","date":"July 10, 2012","format":false,"excerpt":"I have always considered scatterplots to be the best available device to show relationships between variables. But it must be even better to have the regression table and a full description of the results in addition, right? Not so fast: A new paper shows that\u00a0professional economists make largely correct inferences\u2026","rel":"","context":"In &quot;Data visualization&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":720,"url":"http:\/\/re-design.dimiter.eu\/?p=720","url_meta":{"origin":547,"position":4},"title":"The evolution of EU legislation (graphed with ggplot2 and R)","date":"March 19, 2013","format":false,"excerpt":"During the last half century the European Union has adopted more than 100 000 pieces of legislation. In this presentation I look into the patterns of legislative adoption over time. I tried to create clear and engaging graphs that provide some insight into the evolution of law-making activity: not an\u2026","rel":"","context":"In &quot;Data visualization&quot;","img":{"alt_text":"","src":"https:\/\/i1.wp.com\/www.dimiter.eu\/thumb\/figure1.png?resize=350%2C200","width":350,"height":200},"classes":[]},{"id":377,"url":"http:\/\/re-design.dimiter.eu\/?p=377","url_meta":{"origin":547,"position":5},"title":"Visualizing left-right government positions","date":"March 19, 2012","format":false,"excerpt":"How does the political landscape of Europe change over time? One way to approach this question is to map the socio-economic left-right positions of the governments in power. So let's plot the changing ideological \u00a0positions of the governments using data from the Manifesto project! As you will see below, this\u2026","rel":"","context":"In &quot;Data visualization&quot;","img":{"alt_text":"","src":"https:\/\/i0.wp.com\/re-design.dimiter.eu\/wp-content\/uploads\/2012\/03\/rplot2.png?resize=350%2C200","width":350,"height":200},"classes":[]}],"_links":{"self":[{"href":"http:\/\/re-design.dimiter.eu\/index.php?rest_route=\/wp\/v2\/posts\/547"}],"collection":[{"href":"http:\/\/re-design.dimiter.eu\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/re-design.dimiter.eu\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/re-design.dimiter.eu\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/re-design.dimiter.eu\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=547"}],"version-history":[{"count":0,"href":"http:\/\/re-design.dimiter.eu\/index.php?rest_route=\/wp\/v2\/posts\/547\/revisions"}],"wp:attachment":[{"href":"http:\/\/re-design.dimiter.eu\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=547"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/re-design.dimiter.eu\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=547"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/re-design.dimiter.eu\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=547"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}