% \VignetteIndexEntry{Visualize relations by Chord diagram}
% \VignetteDepends{circlize}
% \VignetteKeywords{circos R}
% \VignetteKeywords{Chord Diagram}
% \VignetteKeywords{circlize}
% \VignettePackage{circlize}
%\VignetteCompiler{knitr}
%\VignetteEngine{knitr::knitr}


<<echo = FALSE>>=
library(knitr)
opts_chunk$set(fig.pos = "")

library(circlize)
chordDiagram = function(...) {
    circos.par(unit.circle.segments = 200)
    circlize::chordDiagram(...)
}
@


\documentclass{article}

\usepackage[T1]{fontenc}
\usepackage[sc]{mathpazo}
\renewcommand{\sfdefault}{lmss}
\renewcommand{\ttdefault}{lmtt}

\setcounter{tocdepth}{2}

\title{Visualize Relations by Chord Diagram}

\author{Zuguang Gu {\tt <z.gu@dkfz.de>}}
\usepackage[margin=1in, a4paper]{geometry}

\usepackage{hyperref}

\begin{document}

\maketitle 

One unique feature of circular layout is the links (or connectors) to represent relations
between elements (\url{http://circos.ca/intro/tabular_visualization/}). The name
of such plot is sometimes called Chord Diagram (\url{http://en.wikipedia.org/wiki/Chord_diagram}). 
In \textbf{circlize}, it is easy to plot it in a straightforward or customized way.

There are two data formats that represent relations, either adjacency matrix or adjacency list.
In adjacency matrix, value in $i^{th}$ row and $j^{th}$ column represents the relation from element
in the $i^{th}$ row and the element in the $j^{th}$ column. The absolute value measures the strength
of the relation. In adjacency list, relations are represented as a three-column data frame in which
relations come from the first column and end at the second column, the third column represents the strength
of the relation.

In following code, there is a connection from {\tt b} to {\tt B} and the strength of the connection is 5. 

<<>>=
mat = matrix(1:9, 3)
rownames(mat) = letters[1:3]
colnames(mat) = LETTERS[1:3]
mat
@

While in following code, there is a connection from {\tt b} to {\tt B} with the strength 2.

<<>>=
df = data.frame(from = letters[1:3], to = LETTERS[1:3], value = 1:3)
df
@

In {\bf circlize} package, there is a {\tt chordDiagram} function that supports both adjacency matrix
and adjacency list. The function will dispatch to {\tt chordDiagramFromMatrix} or {\tt chordDiagramFromDataFrame}
according to whether the input is a matrix or a data frame.
Internally, the adjacency matrix is converted to a adjacency list and makes the final Chord diagram by {\tt chordDiagramFromDataFrame}, 
but the adjacency matrix still has some unique features such visualizing a sysmmetric matrix.
Users are encouraged to use {\tt chordDiagram} directly instead of using the two dispatched functions.

\section{The {\tt chordDiagram} function}

Because for adjacency matrix and adjacency list, most of the settings are the same, we only generate figures
with using the matrix. But still the code for using the adjacency list is demonstrated without executing and the figures are generated
only if necessary.

\subsection{Basic usage}

First let's generate a random matrix and the corresponding adjacency list.
We also eliminate several rows in the data frame for users to see the difference.

<<>>=
set.seed(999)
mat = matrix(sample(18, 18), 3, 6) 
rownames(mat) = paste0("S", 1:3)
colnames(mat) = paste0("E", 1:6)
mat

df = data.frame(from = rep(rownames(mat), times = ncol(mat)),
    to = rep(colnames(mat), each = nrow(mat)),
    value = as.vector(mat),
    stringsAsFactors = FALSE)
df = df[sample(18, 10), ]
df
@

The most simple usage is just calling {\tt chordDiagram} with 
{\tt mat} (figure \ref{fig:chord_diagram_basic} A).

<<chord_diagram_basic_simple, eval = FALSE>>=
chordDiagram(mat)
circos.clear()
@

or call with {\tt df}:

<<eval = FALSE>>=
# code is not run when building the vignette
chordDiagram(df)
circos.clear()
@

The default Chord Diagram consists of a track of labels, a track of grids with axes added, and links.
Under default settings, the grid colors are randomly generated,
and the link colors are same as grid colors which correspond to rows but with 50\% transparency. 
The order of sectors is the order of {\tt union(rownames(mat), colnames(mat))}
or {\tt union(df[[1]], df[[2]])} if input is a data frame.

Since Chord Diagram is implemented by \textbf{circlize} package, like normal circos plot,
there are a lot of settings that can be configured.

The gaps between sectors can be set through {\tt circos.par} (figure \ref{fig:chord_diagram_basic} B). 
It is useful when rows and columns are different measurements (as in {\tt mat}). 
Please note since you change default circos graphical settings, you need to 
use {\tt circos.clear} in the end to reset it.

<<chord_diagram_basic_gap_degree, eval = FALSE>>=
circos.par(gap.degree = c(rep(2, nrow(mat)-1), 10, rep(2, ncol(mat)-1), 10))
chordDiagram(mat)
circos.clear()
@

For the data frame:

<<eval = FALSE>>=
# code is not run when building the vignette
circos.par(gap.degree = c(rep(2, length(unique(df[[1]]))-1), 10, 
                          rep(2, length(unique(df[[2]]))-1), 10))
chordDiagram(df)
circos.clear()
@

Similarly, the start degree for the first sector can also be set through {\tt circos.par}
(figure \ref{fig:chord_diagram_basic} C). Since this setting is the same for using
adjacency matrix and adjacency list, we will not show the code with using the adjacency list
and so is in the remaining part of this vignette.

<<chord_diagram_basic_start_degree, eval = FALSE>>=
circos.par(start.degree = 90)
chordDiagram(mat)
circos.clear()
@

The order of sectors can be controlled by {\tt order} argument 
(figure \ref{fig:chord_diagram_basic} D). Of course, the length of {\tt order} vector 
should be same as the number of sectors.

<<chord_diagram_basic_order, eval = FALSE>>=
chordDiagram(mat, order = c("S1", "E1", "E2", "S2", "E3", "E4", "S3", "E5", "E6"))
@

<<chord_diagram_basic, echo = FALSE, fig.align = "center", out.width = "\\textwidth", fig.cap = "Basic usages of {\\tt chordDiagram}. A) default style; B) set {\\tt gap.degree}; C) set {\\tt start.degree}; D) set orders of sectors.">>=
par(mfrow = c(2, 2))
<<chord_diagram_basic_simple>>
text(-0.9, 0.9, "A", cex = 1.5)
<<chord_diagram_basic_gap_degree>>
text(-0.9, 0.9, "B", cex = 1.5)
<<chord_diagram_basic_start_degree>>
text(-0.9, 0.9, "C", cex = 1.5)
<<chord_diagram_basic_order>>
text(-0.9, 0.9, "D", cex = 1.5)
par(mfrow = c(1, 1))
@

\subsection{Colors}

Setting colors is flexible. Colors for grids can be set through {\tt grid.col}.
Values of {\tt grid.col} should be a named vector of which names correspond to sector names.
If {\tt grid.col} has no name index, the order of {\tt grid.col} corresponds to the order of sector names.
As explained before, the default link colors are same
as grids which correspond to rows or the first column for the data frame(figure \ref{fig:chord_diagram_color} A).

<<chord_diagram_color_grid, eval = FALSE>>=
grid.col = c(S1 = "red", S2 = "green", S3 = "blue",
    E1 = "grey", E2 = "grey", E3 = "grey", E4 = "grey", E5 = "grey", E6 = "grey")
chordDiagram(mat, grid.col = grid.col)
@

Transparency of link colors can be set through {\tt transparency} (figure \ref{fig:chord_diagram_color} B). 
The value should between 0 to 1 in which 0 means no transparency and 1 means full transparency.
Default transparency is 0.5. A value of {\tt NA} means just to ignore the transparency setting.

<<chord_diagram_color_transparency, eval = FALSE>>=
chordDiagram(mat, grid.col = grid.col, transparency = 0)
@

For adjacecy matrix, colors for links can be customized by providing a matrix of colors which correspond to {\tt mat}.
In the following example, we use {\tt rand\_color} which is shipped by \textbf{circlize} package
to generate a random color matrix. Note since {\tt col\_mat} already contains transparency, 
{\tt transparency} will be ignored if it is set (figure \ref{fig:chord_diagram_color} C).

<<chord_diagram_color_mat, eval = FALSE>>=
col_mat = rand_color(length(mat), transparency = 0.5)
dim(col_mat) = dim(mat)  # to make sure it is a matrix
chordDiagram(mat, grid.col = grid.col, col = col_mat)
@

While for ajacency list, colors for links can be customized as a vector.

<<eval = FALSE>>=
# code is not run when building the vignette
col = rand_color(nrow(df))
chordDiagram(df, grid.col = grid.col, col = col)
@

{\tt col} argument can also be a self-defined function which maps values to colors.
Here we use {\tt colorRamp2} which is available in \textbf{circlize} to generate a function
with a list of break points and corresponding colors (figure \ref{fig:chord_diagram_color} D).
This functionality also works for adjacency list.

<<chord_diagram_color_fun, eval = FALSE>>=
col_fun = colorRamp2(range(mat), c("#FFEEEEEE", "#FF0000"))
chordDiagram(mat, grid.col = grid.col, col = col_fun)
@

Sometimes you don't need to generate the whole color matrix. You can just provide
colors which correspond to rows or columns so that links from a same row/column will
have the same color (figure \ref{fig:chord_diagram_color} E, F). Here note values of colors
can be set as numbers, color names or hex code, same as in the traditional R graphics.

<<chord_diagram_color_row_col, eval = FALSE, echo = -2>>=
chordDiagram(mat, grid.col = grid.col, row.col = 1:3)
text(-0.9, 0.9, "E", cex = 1.5)
chordDiagram(mat, grid.col = grid.col, column.col = 1:6)
@

There is no similar settings as {\tt row.col} for ajacency list. 

To emphasize again, transparency of links can be included in {\tt col} or {\tt row.col} 
or {\tt column.col}, if transparency is already set there, {\tt transparency} argument 
will be ignored if it is set.

In {\bf Highlight links} section, we will introduce how to enhance subset of links
by only setting colors to them.


<<chord_diagram_color, echo = FALSE, fig.align = "center", out.width = "0.6\\textheight", out.height = "0.9\\textheight", fig.width = 7, fig.height = 10.5, fig.cap = "Color settings in {\\tt chordDiagram}. A) set {\\tt grid.col}; B) set {\\tt transparency}; C) set {\\tt col} as a matrix; D) set {\\tt col} as a function; E) set {\\tt row.col}; F) set {\\tt column.col}.">>=
par(mfrow = c(3, 2))
<<chord_diagram_color_grid>>
text(-0.9, 0.9, "A", cex = 1.5)
<<chord_diagram_color_transparency>>
text(-0.9, 0.9, "B", cex = 1.5)
<<chord_diagram_color_mat>>
text(-0.9, 0.9, "C", cex = 1.5)
<<chord_diagram_color_fun>>
text(-0.9, 0.9, "D", cex = 1.5)
<<chord_diagram_color_row_col>>
text(-0.9, 0.9, "F", cex = 1.5)
par(mfrow = c(1, 1))
@

\subsection{Other graphic settings for links}

{\tt link.lwd}, {\tt link.lty} and {\tt link.border} control the style of link border. 
All these three parameters can be set either a single scalar or a matrix with names.

If it is set as a single scale, it means all links share the same style (figure \ref{fig:chord_diagram_style} A).

<<chord_diagram_style_scalar, eval = FALSE>>=
chordDiagram(mat, grid.col = grid.col, link.lwd = 2, link.lty = 2, link.border = "black")
@

If it is set as a matrix, it should correspond to rows and columns in {\tt mat}
(figure \ref{fig:chord_diagram_style} B). 

<<chord_diagram_style_fullmat, eval = FALSE>>=
lwd_mat = matrix(1, nrow = nrow(mat), ncol = ncol(mat))
rownames(lwd_mat) = rownames(mat)
colnames(lwd_mat) = colnames(mat)
lwd_mat[mat > 12] = 2

border_mat = matrix(NA, nrow = nrow(mat), ncol = ncol(mat))
rownames(border_mat) = rownames(mat)
colnames(border_mat) = colnames(mat)
border_mat[mat > 12] = "black"

chordDiagram(mat, grid.col = grid.col, link.lwd = lwd_mat, link.border = border_mat)
@

The matrix is not necessary to have same number of rows and columns as in {\tt mat}.
It can also be a sub matrix (figure \ref{fig:chord_diagram_style} C). For rows or columns 
of which the corresponding values are not specified in the matrix, default values are filled in.
But no matter it is a full matrix or a sub matrix, it must have row names and column names
so that the settings can be mapped to the correct links.

<<chord_diagram_style_submatrix, eval = FALSE>>=
border_mat2 = matrix("black", nrow = 1, ncol = ncol(mat))
rownames(border_mat2) = rownames(mat)[2]
colnames(border_mat2) = colnames(mat)

chordDiagram(mat, grid.col = grid.col, link.lwd = 2, link.border = border_mat2)
@

To be more convenient, graphic parameters can be set as a three-column data frame
in which the first two columns correspond to row names and column names, and the 
third column corresponds to the graphic parameters (figure \ref{fig:chord_diagram_style} D). 

<<chord_diagram_style_dataframe, eval = FALSE>>=
lty_df = data.frame(c("S1", "S2", "S3"), c("E5", "E6", "E4"), c(1, 2, 3))
lwd_df = data.frame(c("S1", "S2", "S3"), c("E5", "E6", "E4"), c(2, 2, 2))
border_df = data.frame(c("S1", "S2", "S3"), c("E5", "E6", "E4"), c(1, 1, 1))
chordDiagram(mat, grid.col = grid.col, link.lty = lty_df, link.lwd = lwd_df,
    link.border = border_df)
@

For adjacency list, it is much easier, you only need to set these graphical settings
as a vecotr.

<<eval = FALSE>>=
# code is not run when building the vignette
chordDiagram(df, grid.col = grid.col, link.lty = sample(1:3, nrow(df), replace = TRUE),
    link.lwd = runif(nrow(df))*2, link.border = sample(0:1, nrow(df), replace = TRUE))
@

<<chord_diagram_style, echo = FALSE, fig.align = "center", out.width = "\\textwidth", fig.cap = "Link style settings in {\\tt chordDiagram}. A) graphic parameters set as scalar; B) graphic parameters set as matrix; C) graphic parameters set as sub matrix. D) graphic parameters set as a three-column data frame.">>=
par(mfrow = c(2, 2))
<<chord_diagram_style_scalar>>
text(-0.9, 0.9, "A", cex = 1.5)
<<chord_diagram_style_fullmat>>
text(-0.9, 0.9, "B", cex = 1.5)
<<chord_diagram_style_submatrix>>
text(-0.9, 0.9, "C", cex = 1.5)
<<chord_diagram_style_dataframe>>
text(-0.9, 0.9, "D", cex = 1.5)
par(mfrow = c(1, 1))
@


\subsection{Highlight links by colors}

Sometimes we want to highlight some links to emphasize the importance of such connections.
Highlighting by different link styles are introduced in previous section and here we focus on
highlighting by colors.

The key point for highlighting by colors is to set different color transparency to different links.
For example, if we want to highlight links which correspond to state "S1", we can set
{\tt row.col} with different transparency (figure \ref{fig:chord_diagram_highlight} A).

<<chord_diagram_highlight_row, eval = FALSE>>=
chordDiagram(mat, grid.col = grid.col, row.col = c("#FF000080", "#00FF0010", "#0000FF10"))
@

We can also highlight links with values larger than a cutoff (figure \ref{fig:chord_diagram_highlight} B, C). 
There are at least three ways to do it. First, construct a color matrix and set links
with small values to full transparency.

<<chord_diagram_highlight_mat, eval = FALSE>>=
col_mat[mat < 12] = "#00000000"
chordDiagram(mat, grid.col = grid.col, col = col_mat) 
@

Second, use a color function to generate different colors with different values.
Note this is also workable for adjacency list.

<<chord_diagram_highlight_fun, eval = FALSE>>=
col_fun = function(x) ifelse(x < 12, "#00000000", "#FF000080")
chordDiagram(mat, grid.col = grid.col, col = col_fun)
@

Third, use a three-column data frame to assign colors to links of interest (figure \ref{fig:chord_diagram_highlight} D).

<<chord_diagram_highlight_df, eval = FALSE>>=
col_df = data.frame(c("S1", "S2", "S3"), c("E5", "E6", "E4"), 
    c("#FF000080", "#00FF0080", "#0000FF80"))
chordDiagram(mat, grid.col = grid.col, col = col_df)
@

Just remember if you want to highlight links by colors, make sure to set high or full
transparency to the links that you want to ignore.

Again, for adjacency list, you only need to construct a vector of colors according to
what links you want to highlight.

<<eval = FALSE>>=
# code is not run when building the vignette
col = rand_color(nrow(df))
col[df[[3]] < 10] = "#00000000"
chordDiagram(df, grid.col = grid.col, col = col)
@

<<chord_diagram_highlight, echo = FALSE, fig.align = "center", out.width = "\\textwidth", fig.cap = "Highlight links by colors. A) set {\\tt row.col}; B) set by matrix; C) set by color function; D) set by a three-column data frame.">>=
par(mfrow = c(2, 2))
<<chord_diagram_highlight_row>>
text(-0.9, 0.9, "A", cex = 1.5)
<<chord_diagram_highlight_mat>>
text(-0.9, 0.9, "B", cex = 1.5)
<<chord_diagram_highlight_fun>>
text(-0.9, 0.9, "C", cex = 1.5)
<<chord_diagram_highlight_df>>
text(-0.9, 0.9, "D", cex = 1.5)
par(mfrow = c(1, 1))
@

\subsection{Sort links on sectors}

Orders of links on every sector are adjusted automatically to make them look nice.
But sometimes sorting links according to the width on the sector is useful for detecting potential 
features. {\tt link.sort} and {\tt link.decreasing} can be set to control
the link orders (figure \ref{fig:chord_diagram_link_order}).

<<chord_diagram_link_order1, eval = FALSE>>=
chordDiagram(mat, grid.col = grid.col, link.border = 1, 
    link.sort = TRUE, link.decreasing = TRUE)
text(-0.9, 0.9, "A", cex = 1.5)
chordDiagram(mat, grid.col = grid.col, link.border = 1, 
    link.sort = TRUE, link.decreasing = FALSE)
text(-0.9, 0.9, "B", cex = 1.5)
@

<<chord_diagram_link_order, echo = FALSE, fig.align = "center", out.width = "\\textwidth", out.height = "0.5\\textwidth", fig.width = 7, fig.height = 3.5, fig.cap = "Orders of links. A) set {\\tt link.decreasing} to {\\tt TRUE}; B) set {\\tt link.decreasing} to {\\tt FALSE}.">>=
par(mfrow = c(1, 2))
<<chord_diagram_link_order1>>
par(mfrow = c(1, 1))
@


\subsection{Directional connections}

In some cases, rows and columns represent information of direction (This is also natural for adjacency list). 
Argument {\tt directional}
is used to illustrate such direction. {\tt directional} with value 1 means the direction is from rows
to columns (from the first column to the second column for the adjacency list) while -1 means the direction 
is from columns to rows (from the second column to the first column for the adjacency list).
By default, the roots of links will have unequal height (figure \ref{fig:chord_diagram_directional} A, B, C) 
to represent the directions, and the starting foot of the link is shorter
than the ending foot to give people the feeling that the link is moving out. If this is not what you feel,
you can set {\tt diffHeight} to a negative value.


<<chord_diagram_directional_simple, eval = FALSE, echo = c(1, 3, 5)>>=
chordDiagram(mat, grid.col = grid.col, directional = 1)
text(-0.9, 0.9, "A", cex = 1.5)
chordDiagram(mat, grid.col = grid.col, directional = 1, diffHeight = 0.08)
text(-0.9, 0.9, "B", cex = 1.5)
chordDiagram(mat, grid.col = grid.col, directional = -1)
text(-0.9, 0.9, "C", cex = 1.5)
@

Row names and column names in {\tt mat} can also overlap. In this case, showing directions of the link is 
quite important to distinguish them (figure \ref{fig:chord_diagram_directional} D).

<<>>=
mat2 = matrix(sample(100, 35), nrow = 5)
rownames(mat2) = letters[1:5]
colnames(mat2) = letters[1:7]
mat2
@

<<chord_diagram_directional_overlap, eval = FALSE>>=
chordDiagram(mat2, grid.col = 1:7, directional = 1, row.col = 1:5)
@

If you don't need self-loop for which two roots of a link are in a same sector, 
just set corresponding values to 0 in {\tt mat2} (figure \ref{fig:chord_diagram_directional} E).

<<>>=
mat3 = mat2
for(cn in intersect(rownames(mat3), colnames(mat3))) {
    mat3[cn, cn] = 0
}
mat3
@

<<chord_diagram_directional_non_selfloop, eval = FALSE>>=
chordDiagram(mat3, grid.col = 1:7, directional = 1, row.col = 1:5)
@

If the amount of links is not too large, links with arrows are more intuitionistic
to represent directions (figure \ref{fig:chord_diagram_directional} F). In this case, {\tt direction.type} can be set to {\tt arrows}.
Similar as other graphics parameters for links, the parameters for drawing arrows
can either be a scalar, a matrix with dimension names, or a three-column data frame.

If {\tt link.arr.col} is set as a data frame, only links specified in the data frame
will have arrows. Pleast note this is the only way to draw arrows to subset of links.

<<chord_diagram_directional_arrow, eval = FALSE>>=
arr.col = data.frame(c("S1", "S2", "S3"), c("E5", "E6", "E4"), 
    c("black", "black", "black"))
chordDiagram(mat, grid.col = grid.col, directional = 1, direction.type = "arrows",
    link.arr.col = arr.col, link.arr.length = 0.2)
@

If combining both {\tt arrows} and {\tt diffHeight}, it will give you better visualization effect (figure \ref{fig:chord_diagram_directional} G).

<<chord_diagram_directional_arrow2, eval = FALSE>>=
arr.col = data.frame(c("S1", "S2", "S3"), c("E5", "E6", "E4"), 
    c("black", "black", "black"))
chordDiagram(mat, grid.col = grid.col, directional = 1, 
    direction.type = c("diffHeight", "arrows"),
    link.arr.col = arr.col, link.arr.length = 0.2)
@

There is also another arrow type: {\tt big.arrow} which is efficient to visualize arrows if the width of links are too small
(figure \ref{fig:chord_diagram_directional} H)

<<chord_diagram_directional_arrow3, eval = FALSE>>=
matx = matrix(rnorm(64), 8)
chordDiagram(matx, directional = 1, direction.type = c("diffHeight", "arrows"),
    link.arr.type = "big.arrow")
@

If {\tt diffHeight} is set to a negative value, the start roots are longer than the end roots (figure \ref{fig:chord_diagram_directional} I)

<<chord_diagram_directional_arrow4, eval = FALSE>>=
chordDiagram(matx, directional = 1, direction.type = c("diffHeight", "arrows"),
    link.arr.type = "big.arrow", diffHeight = -0.04)
@

Settings are similar for adjacency list, except by default, connection is from the first column
in the data frame to the second one.

<<eval = FALSE>>=
# code is not run when building the vignette
chordDiagram(df, directional = 1)
@

<<chord_diagram_directional, echo = FALSE, fig.align = "center", out.width = "\\textwidth", out.height = "\\textwidth", fig.width = 10.5, fig.height = 10.5, fig.cap = "Visualization of directional matrix. A) with default settings; B) set difference of two feet of links; C) set the starting feet; D, E) row names and column names have overlaps; F, G, H, I) directions are represented by arrows.">>=
par(mfrow = c(3, 3))
<<chord_diagram_directional_simple>>
<<chord_diagram_directional_overlap>>
text(-0.9, 0.9, "D", cex = 1.5)
<<chord_diagram_directional_non_selfloop>>
text(-0.9, 0.9, "E", cex = 1.5)
<<chord_diagram_directional_arrow>>
text(-0.9, 0.9, "F", cex = 1.5)
<<chord_diagram_directional_arrow2>>
text(-0.9, 0.9, "G", cex = 1.5)
<<chord_diagram_directional_arrow3>>
text(-0.9, 0.9, "H", cex = 1.5)
<<chord_diagram_directional_arrow4>>
text(-0.9, 0.9, "I", cex = 1.5)
par(mfrow = c(1, 1))
@

\subsection{Self-links}

How to set self links dependends on specific scenarios. 
If it is a self link, the two roots will be on a same sector. If the link is plotted in the normal way,
the value for this link would be counted twice and sometimes it causes problems.
If users think the self-link represent as a unchanged state, the link should be degenerated as a 'mountain' with the width corresponding to singular value.
While in another scenario, suppose the connection represents the migration between countries, then
the link should be plotted in the normal way because the two roots contain information of direction
and are two different roots. 

The {\tt self.link} argument can be set to 1 or 2 for these two different scenarios. You may see the difference in figure \ref{fig:chord_diagram_self_link}.

<<chord_diagram_self_link1, eval = FALSE, echo = c(1,2,4)>>=
df2 = data.frame(start = c("a", "b", "c", "a"), end = c("a", "a", "b", "c"))
chordDiagram(df2, grid.col = 1:3, self.link = 1, link.border = 1)
text(-0.9, 0.9, "A", cex = 1.5)
chordDiagram(df2, grid.col = 1:3, self.link = 2, link.border = 1)
text(-0.9, 0.9, "B", cex = 1.5)
@

<<chord_diagram_self_link, echo = FALSE, fig.align = "center", out.width = "\\textwidth", out.height = "0.5\\textwidth", fig.width = 7, fig.height = 3.5, fig.cap = "Deal with self links. A) set {\\tt self.link} to 1; B) set {\\tt self.link} to 2.">>=
par(mfrow = c(1, 2))
<<chord_diagram_self_link1>>
par(mfrow = c(1, 1))
@


\subsection{Symmetric matrix}

{\tt chordDiagram} can also be used to visualize symmetric matrix. If {\tt symmetric}
is set to {\tt TRUE}, only lower triangular matrix without the diagonal will be used. 
Of course, your matrix should be symmetric. In figure \ref{fig:chord_diagram_symmetric},
you can see the difference with specifying {\tt symmetric} or not when visualizing a
symmetric matrix. 

<<chord_diagram_symmetric_show, eval = FALSE>>=
mat3 = matrix(rnorm(25), 5)
colnames(mat3) = letters[1:5]
chordDiagram(cor(mat3), grid.col = 1:5, symmetric = TRUE,
    col = colorRamp2(c(-1, 0, 1), c("green", "white", "red")))
@

<<chord_diagram_symmetric_hidden, eval = FALSE, echo = FALSE>>=
chordDiagram(cor(mat3), grid.col = 1:5, col = colorRamp2(c(-1, 0, 1), c("green", "white", "red")))
@

<<chord_diagram_symmetric, echo = FALSE, fig.align = "center", out.width = "\\textwidth", out.height = "0.5\\textwidth", fig.width = 7, fig.height = 3.5, fig.cap = "Visualization of symmetric matrix. A) set {\\tt symmetric} to {\\tt TRUE}; B) set {\\tt symmetric} to {\\tt FALSE}.">>=
par(mfrow = c(1, 2))
<<chord_diagram_symmetric_show>>
text(-0.9, 0.9, "A", cex = 1.5)
<<chord_diagram_symmetric_hidden>>
text(-0.9, 0.9, "B", cex = 1.5)
par(mfrow = c(1, 1))
@


\section{Advanced usage}

Although the default style of {\tt chordDiagram} is enough for most visualization tasks,
still you can have more configurations on the plot. 

The usage is same for both ajacency matrix and ajacency list, so we only demonstrate
with the matrix.

\subsection{Organization of tracks}

By default, {\tt chordDiagram} which utilizes circos graphics functions will create two tracks,
one track for labels and one track for grids (or plus axes). 

<<echo = 2:3>>=
pdf(NULL)
chordDiagram(mat)
circos.info()
invisible(dev.off())
@


These two tracks can be controlled by {\tt annotationTrack}. Available values 
for this argument are {\tt grid} and {\tt name}. The height of annotation tracks can be 
set through {\tt annotationTrackHeight} which corresponds to values in 
{\tt annotationTrack} (figure \ref{fig:chord_diagram_default_track} A, B, C).
The value in {\tt annotationTrackHeight} is the percentage to the radius of unit circle.
If {\tt grid} is specified in {\tt annotationTrack}, there can also be an additional option
{\tt axis} to set whether add axes on this track.

<<chord_diagram_default_track_simple, eval = FALSE, echo = c(1, 3, 4, 6)>>=
chordDiagram(mat, grid.col = grid.col, annotationTrack = "grid")
text(-0.9, 0.9, "A", cex = 1.5)
chordDiagram(mat, grid.col = grid.col, annotationTrack = c("name", "grid"),
    annotationTrackHeight = c(0.03, 0.01))
text(-0.9, 0.9, "B", cex = 1.5)
chordDiagram(mat, grid.col = grid.col, annotationTrack = NULL)
text(-0.9, 0.9, "C", cex = 1.5)
@


<<chord_diagram_default_track, echo = FALSE, fig.align = "center", out.width = "\\textwidth", fig.cap = "Track organization in {\\tt chordDiagram}. A) only show the grid track; B) set label track and grid track with heights; C) do not add label track or grid track.">>=
par(mfrow = c(2, 2))
<<chord_diagram_default_track_simple>>
par(mfrow = c(1, 1))
@


Several empty tracks can be allocated before Chord diagram is drawn. Then self-defined graphics can
be added to these empty tracks afterwards. The number of pre-allocated tracks can be set 
through {\tt preAllocateTracks}.

<<echo = 2:3>>=
pdf(NULL)
chordDiagram(mat, preAllocateTracks = 2)
circos.info()
invisible(dev.off())
@

The default settings for pre-allocated tracks are:

<<eval = FALSE>>=
list(ylim = c(0, 1),
     track.height = circos.par("track.height"),
     bg.col = NA,
     bg.border = NA,
     bg.lty = par("lty"),
     bg.lwd = par("lwd"))
@

The default settings for pre-allocated tracks can be overwritten by specifying {\tt preAllocateTracks}
as a list.

<<eval = FALSE>>=
chordDiagram(mat, annotationTrack = NULL,
    preAllocateTracks = list(track.height = 0.3))
circos.info(sector.index = "S1", track.index = 1)
@

If more than one tracks need to be pre-allocated, just specify {\tt preAllocateTracks}
as a list which contains settings for each track:

<<eval = FALSE>>=
chordDiagram(mat, annotationTrack = NULL,
    preAllocateTracks = list(list(track.height = 0.1),
                             list(bg.border = "black")))
@

By default {\tt chordDiagram} provides poor support for customization of sector labels and axes, 
but with {\tt preAllocateTracks} it is rather easy to customize them. Such customization will be introduced
in next section.

\subsection{Customize sector labels}

In {\tt chordDiagram}, there is no argument to control the style of sector labels. 
But this can be done by first pre-allocating an empty track and customizing the labels 
in it later. In the following example, one track is firstly allocated and a Chord diagram 
is added without label track. Later, the first track is updated with setting 
{\tt facing} of labels (figure \ref{fig:chord_diagram_labels} A).

<<chord_diagram_labels_show, eval = FALSE>>=
chordDiagram(mat, grid.col = grid.col, annotationTrack = "grid", 
    preAllocateTracks = list(track.height = 0.3))
# we go back to the first track and customize sector labels
circos.trackPlotRegion(track.index = 1, panel.fun = function(x, y) {
    xlim = get.cell.meta.data("xlim")
    ylim = get.cell.meta.data("ylim")
    sector.name = get.cell.meta.data("sector.index")
    circos.text(mean(xlim), ylim[1], sector.name, facing = "clockwise", 
        niceFacing = TRUE, adj = c(0, 0.5))
}, bg.border = NA) # here set bg.border to NA is important
@

In the following example, the labels are put inside the grids (figure \ref{fig:chord_diagram_labels} B).
Please note {\tt get.cell.meta.data} and {\tt circos.text} are used outside of {\tt panel.fun},
so {\tt track.index} and {\tt sector.index} should be specified explicitly.

<<chord_diagram_labels_inside, eval = FALSE>>=
chordDiagram(mat, grid.col = grid.col, 
    annotationTrack = "grid", annotationTrackHeight = 0.15)
for(si in get.all.sector.index()) {
    xlim = get.cell.meta.data("xlim", sector.index = si, track.index = 1)
    ylim = get.cell.meta.data("ylim", sector.index = si, track.index = 1)
    circos.text(mean(xlim), mean(ylim), si, sector.index = si, track.index = 1, 
        facing = "bending.inside", col = "white")
}
@

For the last example, we add the sector labels with different style. If the width of the 
sector is less than 20 degree, the labels are added in the radical direction. 

<<chord_diagram_labels_multile_style, eval = FALSE>>=
mat2 = matrix(rnorm(100), 10)
chordDiagram(mat2, annotationTrack = "grid", preAllocateTracks = list(track.height = 0.1))
circos.trackPlotRegion(track.index = 1, panel.fun = function(x, y) {
    xlim = get.cell.meta.data("xlim")
    xplot = get.cell.meta.data("xplot")
    ylim = get.cell.meta.data("ylim")
    sector.name = get.cell.meta.data("sector.index")

    if(abs(xplot[2] - xplot[1]) < 20) {
        circos.text(mean(xlim), ylim[1], sector.name, facing = "clockwise",
            niceFacing = TRUE, adj = c(0, 0.5))
    } else {
        circos.text(mean(xlim), ylim[1], sector.name, facing = "inside", 
            niceFacing = TRUE, adj = c(0.5, 0))
    }
}, bg.border = NA)
@


<<chord_diagram_labels, echo = FALSE, fig.align = "center", out.width = "\\textwidth", fig.cap = "Customize sector labels. A) put sector labels in radical direction; B) sector labels are put inside grids; C) sector labels are put in different direction according the width of sectors.">>=
par(mfrow = c(2, 2))
<<chord_diagram_labels_show>>
text(-0.9, 0.9, "A", cex = 1.5)
<<chord_diagram_labels_inside>>
text(-0.9, 0.9, "B", cex = 1.5)
circos.par(points.overflow.warning = FALSE)
<<chord_diagram_labels_multile_style>>
circos.clear()
text(-0.9, 0.9, "C", cex = 1.5)
par(mfrow = c(1, 1))
@

One last thing, when you set direction of sector labels as radical ({\tt clockwise} or {\tt reverse.clockwise}, if the labels are too long
and exceed your figure region, you can either decrease the size of the font or set 
{\tt canvas.xlim} and {\tt canvas.ylim} to wider intervals. 

\subsection{Customize sector axes}

Axes are helpful to visualize the absolute values of links. By default {\tt chordDiagram}
add axes on the grid track. But it is easy to customize a better one with self-defined code.

Another type of axes which show relative percent is also helpful for visualizing Chord diagram.
Here we pre-allocate an empty track by {\tt preAllocateTracks} and come back to this track
to add axes later. In following example, a major tick is put every 25\% in each sector.
And the axes are only added if the sector width is larger than 20 degree (figure \ref{fig:chord_diagram_axes}).

<<chord_diagram_axes_two, eval = FALSE>>=
# similar as the previous example, but we only plot the grid track
chordDiagram(mat, grid.col = grid.col, annotationTrack = "grid", 
    preAllocateTracks = list(track.height = 0.1))
for(si in get.all.sector.index()) {
    circos.axis(h = "top", labels.cex = 0.3, major.tick.percentage = 0.2,
        sector.index = si, track.index = 2)
}

# the second axis as well as the sector labels are added in this track
circos.trackPlotRegion(track.index = 1, panel.fun = function(x, y) {
    xlim = get.cell.meta.data("xlim")
    xplot = get.cell.meta.data("xplot")
    ylim = get.cell.meta.data("ylim")
    sector.name = get.cell.meta.data("sector.index")
    
    if(abs(xplot[2] - xplot[1]) > 20) {
        circos.lines(xlim, c(mean(ylim), mean(ylim)), lty = 3) # dotted line
        for(p in seq(0.2, 1, by = 0.2)) {
            circos.text(p*(xlim[2] - xlim[1]) + xlim[1], mean(ylim) + 0.1, 
                p, cex = 0.3, adj = c(0.5, 0), niceFacing = TRUE)
        }
    }
    circos.text(mean(xlim), 1, sector.name, niceFacing = TRUE, adj = c(0.5, 0))
}, bg.border = NA)
circos.clear()
@


<<chord_diagram_axes, echo = FALSE, fig.align = "center", out.width = "0.5\\textwidth", out.height = "0.5\\textwidth", fig.width = 3.5, fig.height = 3.5, fig.cap = "Customize sector axes">>=
<<chord_diagram_axes_two>>
@


\subsection{Compare two Chord diagrams}

Normally, in Chord diagram, values in {\tt mat} are normalized to the summation (of the absolute values) and each value is put to 
the circle according to its percentage, which means the width for each link only 
represents kind of relative value. However, when comparing two Chord diagrams, 
it is necessary that unit width of links in the two plots should be represented in 
a same scale. This problem can be solved by adding more blank gaps to the Chord diagram 
which has smaller values.

First, let's plot a Chord diagram. In this Chord diagram, we set larger gaps between rows
and columns for better visualization. Axis on the grid illustrates scale of the values.

<<chord_diagram_compare_1, eval = FALSE>>=
mat1 = matrix(sample(20, 25, replace = TRUE), 5)

gap.degree = c(rep(2, 4), 10, rep(2, 4), 10)
circos.clear()
circos.par(gap.degree = gap.degree, start.degree = -10/2)
chordDiagram(mat1, directional = 1, grid.col = rep(1:5, 2))
circos.clear()
@

The second matrix only has half the values in {\tt mat1}.

<<chord_diagram_compare_2, eval = FALSE>>=
mat2 = mat1 / 2
@

If the second Chord diagram is plotted in the way as the first one, the two diagrams will looks 
exactly the same which makes the comparison impossible. What we want to compare between two diagrams is
the absolute values. For example, if the matrix contains the amount of transitions from one state
to another state, then the interest is to see which diagram has more transitions.

First we calculate the percentage of {\tt mat2} in {\tt mat1}. And then we calculate the degree
which corresponds to the difference. In the following code, {\tt 360 - sum(gap.degree)}
is the total degree for values in {\tt mat1} (excluding the gaps) and {\tt blank.degree} 
corresponds the difference between {\tt mat1} and {\tt mat2}.

<<chord_diagram_compare_3, eval = FALSE>>=
percent = sum(abs(mat2)) / sum(abs(mat1))
blank.degree = (360 - sum(gap.degree)) * (1 - percent)
@

Since now we have the additional blank gap, we can set it to {\tt circos.par} and plot the second Chord Diagram.

<<chord_diagram_compare_4, eval = FALSE>>=
big.gap = (blank.degree - sum(rep(2, 8)))/2
gap.degree = c(rep(2, 4), big.gap, rep(2, 4), big.gap)
circos.par(gap.degree = gap.degree, start.degree = -big.gap/2)
chordDiagram(mat2, directional = 1, grid.col = rep(1:5, 2), transparency = 0.5)
circos.clear()
@

Now the scale of the two Chord diagrams (figure \ref{fig:chord_diagram_compare}) are the 
same if you look at the scale of axes in the two diagrams.

<<chord_diagram_compare, echo = FALSE, fig.align = "center", out.width = "\\textwidth", out.height = "0.5\\textwidth", fig.width = 7, fig.height = 3.5, fig.cap = "Compare two Chord Diagrams and make them in same scale. bottom matrix has half the values as in the upper matrix.">>=
par(mfrow = c(1, 2))
<<chord_diagram_compare_1>>
text(-0.9, 0.9, "A", cex = 1.5)
<<chord_diagram_compare_2>>
<<chord_diagram_compare_3>>
<<chord_diagram_compare_4>>
text(-0.9, 0.9, "B", cex = 1.5)
par(mfrow = c(1, 1))
@


\section{Misc}

If a sector in Chord Diagram is too small, it will be removed from the original matrix.
In the following matrix, the second row and third column contain tiny numbers.

<<>>=
mat = matrix(rnorm(36), 6, 6)
rownames(mat) = paste0("R", 1:6)
colnames(mat) = paste0("C", 1:6)
mat[2, ] = 1e-10
mat[, 3] = 1e-10
@

If you only want to remove some of the links, set corresponding values to 0.

In the Chord Diagram, categories corresponding to the second row and the third column will
be removed (figure \ref{fig:chord_diagram_reduce} A).

<<chord_diagram_reduce_1, eval=FALSE>>=
chordDiagram(mat)
@

If you set {\tt row.col}, {\tt column.col} or {\tt col} to specify the colors of the links,
colors corresponding to the second row and the third column will also be removed (figure \ref{fig:chord_diagram_reduce} B).

<<chord_diagram_reduce_2, eval=FALSE>>=
chordDiagram(mat, row.col = rep(c("red", "blue"), 3))
@

{\tt grid.col} is reduced if it is set as a vector
which has the same length as categories which are from the unreduced matrix (figure \ref{fig:chord_diagram_reduce} C).

<<chord_diagram_reduce_3, eval=FALSE>>=
chordDiagram(mat, grid.col = rep(c("red", "blue"), 6))
circos.clear()
@

{\tt circos.par("gap.degree")} will be reduced as well (figure \ref{fig:chord_diagram_reduce} D).

<<chord_diagram_reduce_4, eval=FALSE>>=
circos.par("gap.degree" = rep(c(2, 10), 6))
chordDiagram(mat)
circos.clear()
@


<<chord_diagram_reduce, echo = FALSE, fig.align = "center", out.width = "\\textwidth", fig.cap = "Reduced Chord Diagram with removing tiny sectors. A) notice how sector labels are reduced; B) notice how link colors are reduced; C) notice how grid colors are reduced; D) notice how gap degrees are reduced.">>=
par(mfrow = c(2, 2))
<<chord_diagram_reduce_1>>
text(-0.9, 0.9, "A", cex = 1.5)
<<chord_diagram_reduce_2>>
text(-0.9, 0.9, "B", cex = 1.5)
<<chord_diagram_reduce_3>>
text(-0.9, 0.9, "C", cex = 1.5)
<<chord_diagram_reduce_4>>
text(-0.9, 0.9, "D", cex = 1.5)
@


\end{document}
