<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/filled-chord-diagram-in-r-using-plotly/"></div></div><div><a data-url="https://www.r-bloggers.com/filled-chord-diagram-in-r-using-plotly/" data-counturl="https://www.r-bloggers.com/filled-chord-diagram-in-r-using-plotly/" data-count="horizontal" data-text="Filled Chord Diagram in R using Plotly" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://moderndata.plot.ly/filled-chord-diagram-in-r-using-plotly/"> R – Modern Data</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>In this post we’ll create a <a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/Chord_diagram">Filled Chord Diagram</a> using plotly. The post is inspired by <a target="_blank" rel="nofollow" href="https://plot.ly/python/filled-chord-diagram/">Plotly’s Python documentation</a>.</p>
<div>
<h2>Install / update packages</h2>
<p>Just to ensure we are working with the latest dev version of plotly.</p>

<pre># Install packages if needed
# install.packages(c(&quot;devtools&quot;, &quot;dplyr&quot;))
# library(devtools)
# install_github(&quot;ropensci/plotly&quot;)

library(plotly)
library(dplyr)</pre>

</div>
<div>
<h2>Dataset</h2>
<p>The dataset we’ll use consists of the number of comments a person made on her own facebook posts as well as the number of comments on her friend’s facebook posts.</p>

<pre># Dataset for creating chord diagram ------------------------------------------
# Data for number of facebook posts
# See https://plot.ly/python/filled-chord-diagram/

df &lt;- rbind(c(16, 3, 28, 0, 18),
            c(18, 0, 12, 5, 29),
            c(9, 11, 17, 27, 0),
            c(19, 0, 31, 11, 12),
            c(23, 17, 10, 0, 34))
df &lt;- data.frame(df)

colnames(df) &lt;- c('Emma', 'Isabella', 'Ava', 'Olivia', 'Sophia')
rownames(df) &lt;- c('Emma', 'Isabella', 'Ava', 'Olivia', 'Sophia')</pre>

</div>
<div>
<h2>Global settings</h2>
<p>These are some plot related settings which we can setup right now. These settings will be fed to <code>plot_ly()</code> later on. Also, having these aesthetic settings accessible now will make it easier for us to make changes later on.</p>

<pre># Settings --------------------------------------------------------------------
# Over all plot settings like color and transparency

cols &lt;- RColorBrewer::brewer.pal(nrow(df), &quot;Set1&quot;)  # Set of colors (n = number of rows in data)
opacity &lt;- 0.5  # Opacity of ideogram
chord.opacity &lt;- 0.3  # Opcaity of individual chords
linecolor &lt;- &quot;black&quot;
circlefill &lt;- &quot;#f2f2f2&quot;
inner.radius &lt;- 0.93
gap &lt;- 0.02</pre>

</div>
<div>
<h2>Creating the Ideogram</h2>
<p>We’ll first create the ideogram. The ideogram which is essentially a set of sectors plotted on a unit circle which’ll represent the rowsums of the dataset i.e. the total number of comments made by each person (to themselves and their friends). We’ll first create some helper functions – <code>toAngular()</code> to map a vector of numeric values onto the unit circle using cumulative sums essentially creating sectors and <code>addGaps()</code> which’ll create some space between each sector for aesthetic purposes.</p>

<pre># Function Definition: addGaps() ----------------------------------------------
addGaps &lt;- function(theta, gap = 0.05){
  
  # Takes a vector of angles and adds a gap in-between them
  # Adds and subtracts the gap value from computed angle
  
  newtheta &lt;- data.frame()
  
  for (i in 1:length(theta)) {
    
    if(i == 1){
      x &lt;- 0 + gap
      y &lt;- theta[i] - gap
      newtheta &lt;- rbind(newtheta, c(x, y))
    }else{
      x &lt;- theta[i - 1] + gap
      y &lt;- theta[i] - gap
      newtheta &lt;- rbind(newtheta, c(x, y))
    }
  }
  
  newtheta &lt;- data.frame(theta, newtheta)
  colnames(newtheta) &lt;- c(&quot;theta&quot;, &quot;start&quot;, &quot;end&quot;)
  
  return(newtheta)
}

# Function Definition: toAngular() --------------------------------------------
toAngular &lt;- function(x, rad = 1, gap = 0.05, lower = 0, upper = 2*pi, addgaps = T){
  
  # Maps a set of numbers onto the unit circle by computing cumulative
  # sums and assigning angles to each sum
  
  cumtotals &lt;- cumsum(x / sum(x))
  
  # Upper and lower bounds are the angle limits to which mapping
  # is limited. Ex 0 - 2PI
  delta &lt;- ifelse(upper > lower, upper - lower, (2*pi) - lower + upper)
  theta &lt;-  cumtotals * delta
  
  x &lt;- rad * cos(theta)
  y &lt;- rad * sin(theta)
  
  df &lt;- data.frame(x, y)
  
  # Additionally, add gaps in between each sector using the addGaps() function
  if (addgaps == T) {
    gaps &lt;- addGaps(theta, gap = gap)
    ret &lt;- list(theta = theta,
                coord = df,
                gaps = gaps)
  }else{
    ret &lt;- list(theta = theta,
                coord = df)
  }
  
  return(ret)
}</pre>

<p>Now that the functions are defined we need to create the ideogram. We do so by:</p>
<ol>
<li>Creating an outer ring which’ll lie on the unit circle</li>
<li>Creating an inner ring which lie inside the outer circle (radius is defined in the settings section above)</li>
<li>Creating an SVG path for each sector bounded by the outer and inner circles and the end points of each gap</li>
</ol>
<pre># Create ideogram -------------------------------------------------------------
# See See https://plot.ly/python/filled-chord-diagram/

# The ideogram is constructed of the row sums i.e total interactions in each row
dat &lt;- rowSums(df)

# Outer ring is the unit circle
outer &lt;- toAngular(dat, gap = gap)

# Inner ring has radius &lt; 1
inner &lt;- toAngular(dat, rad = inner.radius, gap = gap)

# Ideogram is charted as a svg path and fed to plot_ly() as a shape
# Compute a path for each sector of the ideogram by combining the 
# coordinates of the outer and inner circles
outer.inner &lt;- rbind(outer$gaps, inner$gaps) %>% arrange(theta)  # arrange in increasing order of theta

# Each sector of the ideogram is made of four points - 
# the start and end points of the outer and inner circles
# Hence increment by 2 and not 1
vec &lt;- seq(1, nrow(outer.inner), by = 2)

# Create and empty dataframe
ideogram &lt;- data.frame()

k &lt;- 1  # Counter for each row / group

# Loop through each sector and create a svg path using the start and end
# points of the outer and inner circles
for (i in vec) {
  
  # Get starting and ending point for 'i' th sector
  start &lt;- outer.inner$start[i]
  end &lt;- outer.inner$end[i]
  
  # Ensure starting point is always less than ending point of sector
  if (start > end) start &lt;- start - (2*pi)
  
  # Create a sequence of thetas along the sector
  thetas &lt;- seq(start, end, length.out = 100)
  
  # Compute x and y coordinates
  x &lt;- c(cos(thetas), inner.radius * cos(rev(thetas)))
  y &lt;- c(sin(thetas), inner.radius * sin(rev(thetas)))
  
  # Add a group for easy subsetting later on
  coords &lt;- data.frame(x, y, group = k)
  ideogram &lt;- rbind(ideogram, coords)
  
  # Increment group number
  k &lt;- k + 1
}

# Function definition: createPath() -------------------------------------------
createPath &lt;- function(df){
  
  # Given x and y coordinates creates a string containing a svg path
  # that can be fed to plotly as a shape
  
  start &lt;- paste(&quot;M&quot;, df$x[1], df$y[1])
  path &lt;- paste(&quot;L&quot;, df$x[-1], df$y[-1], collapse = &quot; &quot;)
  path &lt;- paste(start, path, &quot;Z&quot;)
  return(path)
}

# Use group numbers assigned to each sector to subset and create a path string
ideogram.path &lt;- by(ideogram, ideogram$group, createPath)

# Plot the ideogram (just as a check). Chord diagram is generated separately later
# Create shape list
ideogram.shapes &lt;- list()  # Used later on

for (i in 1:nrow(df)) {
  
  # Use plotly syntax to save shapes of each sector as a list
  ideogram.shapes[[i]] &lt;- list(type = &quot;path&quot;,
                               path = ideogram.path[i],
                               fillcolor = cols[i],
                               line = list(color = linecolor, width = 1),
                               opacity = opacity)
}

# Just to check if things are looking okay
ideogram.plot &lt;- plot_ly(height = 800, width = 800) %>%
  layout(
    xaxis = list(showgrid = F, zeroline = F, showticklabels = F),
    yaxis = list(showgrid = F, zeroline = F, showticklabels = F),
    shapes = ideogram.shapes)

ideogram.plot</pre>

<p>You should now have something similar to this: <iframe height="800" width="900" src="http://plot.ly/~riddhiman/397.embed"></iframe></p>
</div>
<div>
<h2>Creating Chords</h2>
<p>The following set of code snippets essentially do this:</p>
<ol>
<li>
<p>Divide each sector on the ideogram into sub – sectors based on the number of comments made by each person i.e. traverse the dataset row-wise and map the numeric vectors in each row onto the associated sector (not the unit circle). Example: Emma has a total of 65 comments amongst herself and her friends. The sector corrosponding to Emma’s 65 comments needs to be divided into further sectors based on the 16, 3, 28, 0 and 18 comments.</p>
</li>
<li>
<p>Find the four points that bind each chord. A chord is a planar shape that is bound by two bezier curves and two circular arcs. For each bezier curve the control point is generated by finding the mean of the angluar coordinates of the end points.</p>
</li>
<li>
<p>Fill each chord (ribbon) with the appropriate color. Example: Emma made 18 comments on Sophia’s posts but Sophia made 23 comments on Emma’s posts. Since Sophia made more comments, the chord depicting the interaction betweem Emma and Sophia is colored using the same color that is used for coloring Sophia’s sector on the ideogram.</p>
</li>
<li>
<p>Create SVG shapes for each chord and then plot using <code>plot_ly()</code></p>
</li>
</ol>
<p><strong>Note that the ordering of the endpoints of bezier curves and circular arcs is tricky and was done based on trial and error.</strong></p>

<pre># Create chords ---------------------------------------------------------------
# Divide each sector corresponding to each interaction in each row
sector.angles &lt;- inner$gaps
angle.list &lt;- data.frame()
for (i in 1:nrow(sector.angles)) {
  # Get starting and ending points of each sector
  start &lt;- sector.angles$start[i]
  end &lt;- sector.angles$end[i]
  
  # Sort each row from increasing to decreasing
  dat &lt;- sort(df[i,])
  
  # Use toAngular() function to get thetas corrosponding to each row item
  angle &lt;- toAngular(as.numeric(dat), lower = start, upper = end, addgaps = F)$theta
  
  # Offset by the starting point since the function returns values in 
  # the [0 - (start - end)] interval
  angle &lt;- c(start + angle)
  
  # Collate all the data for each division of the sector 
  temp &lt;- data.frame(from = rownames(sector.angles)[i],
                     to = names(dat),
                     value = as.numeric(dat),
                     angle,
                     x = inner.radius * cos(angle),
                     y = inner.radius * sin(angle),
                     stringsAsFactors = F)
  
  # Add the starting point to the divisions
  # If min value in a row is zero then starting point for that division
  # must be the starting point of the sector
  startrow &lt;- data.frame(from = rownames(sector.angles)[i],
                         to = &quot;start&quot;,
                         value = 0,
                         angle = sector.angles$start[i],
                         x = inner.radius * cos(sector.angles$start[i]),
                         y = inner.radius * sin(sector.angles$start[i]),
                         stringsAsFactors = F)
  
  angle.list &lt;- rbind(angle.list, startrow, temp)
}

# Create unique path IDs i.e. each set of interactions gets a unique ID
# Example - A -> B and B -> A will get the same ID
k &lt;- 1
angle.list$ID &lt;- rep(0, nrow(angle.list))
revstr &lt;- paste(angle.list$to, angle.list$from)

for (i in 1:nrow(angle.list)) {
  if (angle.list$ID[i] == 0) {
    from = angle.list$from[i]
    to = angle.list$to[i]
    str &lt;- paste(from, to)
    mtch &lt;- match(str, revstr)
    
    if (!is.na(mtch)) {
      angle.list$ID[c(i, mtch)] &lt;- k
      k &lt;- k + 1
    }
  }
}

# Each chord is bounded by four points: 
# 1. two actual data points corrosponding to the actual interaction i.e. A -> B (p1) and B -> A (p2)
# 2. And two previous data points to complete the polygon
# We'll create some helper functions

# Function definition: bezierCurve() ------------------------------------------
bezierCurve &lt;- function(t1, t2){
  
  # Takes two angles as arguments and returns the x and y coordinates
  # of a quadratic bezier curve 
  
  t &lt;- seq(0, 1, length.out = 100)
  
  p0 &lt;- c(inner.radius * cos(t1), inner.radius * sin(t1))  # Starting point (t1)
  p2 &lt;- c(inner.radius * cos(t2), inner.radius * sin(t2))  # Ending point (t2)
  p1 &lt;- c(-inner.radius * cos(mean(t1, t2)), -inner.radius * sin(mean(t1, t2)))  # Control point
  
  # Curve =  (1 - t^2)*p0 + 2(t-1)t*p1 + t^2*p2
  x &lt;- (1 - t**2) * p0[1] + 2*(1 - t)*t * p1[1] + t**2 * p2[1]
  y &lt;- (1 - t**2) * p0[2] + 2*(1 - t)*t * p1[2] + t**2 * p2[2]
  df &lt;- data.frame(x, y)
  
  return(df)
}

# Function definition: circleCurve() ------------------------------------------
circleCurve &lt;- function(t1, t2){

  # Returns the x and y coordinates of points lying on the inner 
  # boundary of the ideogram bounded by two angles t1 and t2 
    
  t &lt;- seq(min(t1, t2), max(t1, t2), length.out = 50)
  x &lt;- inner.radius * cos(t)
  y &lt;- inner.radius * sin(t)
  
  df &lt;- data.frame(x, y)
  
  return(df)
}

# Function definition: opposite() ---------------------------------------------
opposite &lt;- function(df){
  
  # Given a dataframe, simply returns the dataframe in reverse order
  
  n &lt;- nrow(df)
  df &lt;- df[n:1,]
  return(df)
}

# Function definition: chordShape() -------------------------------------------
chordShape &lt;- function(ID){
  
  # Function to create svg path for a chord given by a unique ID (created earler)
  
  id &lt;- which(angle.list$ID == ID)
  
  # Get color based on higher number of connects
  idx &lt;- which.max(angle.list$value[id])
  fillcolor &lt;- angle.list$from[id[idx]]
  fillcolor &lt;- cols[which(rownames(df) == fillcolor)]
  
  # Append the two prior points to complete polygon
  id &lt;- c(id, id - 1)
  t &lt;- angle.list$angle[id]
  
  # Each chord is made of two bezier curves and two (one) curve lying on the 
  # inner boundary of the ideogram
  if(length(t) == 4){
    a &lt;- bezierCurve(t[1], t[4])
    b &lt;- bezierCurve(t[3], t[2])
    c &lt;- circleCurve(t[1], t[3])
    d &lt;- circleCurve(t[2], t[4])
    
    df &lt;- rbind(a, d, opposite(b), c)
    
    pth &lt;- createPath(df)
    shp &lt;- list(type = &quot;path&quot;,
                path = pth,
                fillcolor = fillcolor,
                line = list(color = linecolor, width = 1),
                opacity = chord.opacity)
    
  }else{
    
    # Case when there are zero interactions i.e. 
    # A -> B > 0 but B -> A = 0 or viceversa
    a &lt;- bezierCurve(t[1], t[2])
    b &lt;- circleCurve(t[1], t[2])
    
    df &lt;- rbind(a, b)
    
    pth &lt;- createPath(df)
    shp &lt;- list(type = &quot;path&quot;,
                path = pth,
                fillcolor = fillcolor,
                line = list(color = linecolor, width = 1),
                opacity = chord.opacity)
  }
  
  return(shp)
}

# Loop through each unique ID and create a shape for each corrosponding polygon
chord.shapes &lt;- list()
for(i in unique(angle.list$ID)){
  if(i != 0){
    chord.shapes[[i]] &lt;- chordShape(ID = i)
  }
}

# Create a grey circle on the inside for aesthetics
ang &lt;- seq(0, (2*pi), length.out = 100)
x &lt;- 1 * cos(ang)
y &lt;- 1 * sin(ang)

pth &lt;- createPath(df = data.frame(x, y))
inner.circle &lt;- list(list(type = &quot;path&quot;,
                          path = pth,
                          fillcolor = circlefill,
                          line = list(color = linecolor, width = 1),
                          opacity = 0.2))

# Add all shapes to same list
all.shapes &lt;- c(ideogram.shapes, chord.shapes, inner.circle)
length(all.shapes)

# Plot chord diagram ----------------------------------------------------------
# Just a description of chord diagram
description &lt;- paste0(&quot;&lt;i>&quot;,&quot;A chord diagram is a graphical method of displaying the inter-relationships &quot;,
                      &quot;between data in a matrix. The data is &lt;br> arranged radially around a circle &quot;,
                      &quot;with the relationships between the points typically drawn as arcs connecting &quot;,
                      &quot;the&lt;br>data together - &lt;b>Wikipedia&lt;/b>&quot;,&quot;&lt;/i>&quot;)

# Coordinates for labels
labels &lt;- data.frame(x = 1.1 * cos(outer$theta + pi/5),
                     y = 1.1 * sin(outer$theta + pi/5),
                     text = paste0(&quot;&lt;b>&quot;, rownames(df), &quot;&lt;/b>&quot;))

# Plot using plot_ly()
chord.plot &lt;- plot_ly(width = 800, height = 800) %>%
  
  # Add labels to sectors
  add_text(data = labels, x = ~x, y = ~y, text = ~text, hoverinfo = &quot;none&quot;,
           textfont = list(family = &quot;serif&quot;, size = 14, color = &quot;#999999&quot;)) %>%
  
  # Layout for shapes, annotations and axis options
  layout(
    xaxis = list(title = &quot;&quot;, showgrid = F, zeroline = F, showticklabels = F, domain = c(0, 0.9)),
    yaxis = list(title = &quot;&quot;, showgrid = F, zeroline = F, showticklabels = F, domain = c(0, 0.9)),
    shapes = all.shapes,
    
    annotations = list(
      list(xref = &quot;paper&quot;, yref = &quot;paper&quot;,
           xanchor = &quot;left&quot;, yanchor = &quot;top&quot;,
           x = 0, y = 1, showarrow = F,
           text = &quot;&lt;b>Filled Chord Diagram&lt;/b>&quot;,
           font = list(family = &quot;serif&quot;, size = 25, color = &quot;black&quot;)),
      
      list(xref = &quot;paper&quot;, yref = &quot;paper&quot;,
           xanchor = &quot;left&quot;, yanchor = &quot;top&quot;,
           x = 0, y = 0.95, showarrow = F,
           text = description,
           align = &quot;left&quot;,
           font = list(family = &quot;arial&quot;, size = 10, color = &quot;black&quot;))
    ))

print(chord.plot)</pre>

<p>You should now have something like this: <iframe height="800" width="900" target="_blank" src="http://plot.ly/~riddhiman/385.embed"></iframe></p>
<p>I am sure there are more efficient ways of going about this but hopefully you found this post helpful. Here are some additional resources to look at:</p>
<ol>
<li><a target="_blank" rel="nofollow" href="https://plot.ly/python/filled-chord-diagram/">Plotly Python documentaion</a></li>
<li><a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/Chord_diagram">Chord Diagram Wikipedia</a></li>
<li><a target="_blank" rel="nofollow" href="https://bl.ocks.org/mbostock/4062006">Mike Bostock’s Block</a></li>
<li><a target="_blank" rel="nofollow" href="http://www.visualcinnamon.com/2014/12/using-data-storytelling-with-chord.html">Nice tutorial on Visual Cinnamon</a></li>
<li><a target="_blank" rel="nofollow" href="http://stackoverflow.com/questions/14599150/chord-diagram-in-r">Stack Overflow question</a></li>
</ol>
</div>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="https://www.r-bloggers.com/filled-chord-diagram-in-r-using-plotly/"></div></div><div><a data-url="https://www.r-bloggers.com/filled-chord-diagram-in-r-using-plotly/" data-counturl="https://www.r-bloggers.com/filled-chord-diagram-in-r-using-plotly/" data-count="vertical" data-text="Filled Chord Diagram in R using Plotly" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://moderndata.plot.ly/filled-chord-diagram-in-r-using-plotly/"> R – Modern Data</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/?s=Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/3ULlehYnpR0"></a></div>