% \VignetteIndexEntry{Introduction to circlize package}
% \VignetteDepends{circlize}
% \VignetteKeywords{circos R}
% \VignetteKeywords{ideogram}
% \VignetteKeywords{circlize}
% \VignettePackage{circlize}
%\VignetteCompiler{knitr}
%\VignetteEngine{knitr::knitr}


\documentclass{article}

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

\setcounter{tocdepth}{2}

\title{An introduction to \textbf{circlize} package}

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

\usepackage{hyperref}

\begin{document}

\maketitle 


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

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


Circular layout is very useful to represent complicated information, especially for genomic data. It 
has advantages to visualize data with long axes or large amount of categories, described with different measurements. 
It is also effective to visualize relations between elements.

\textbf{Circos} (\url{http://circos.ca}) is an extraordinarily cool tool to make such circular layout and it is broadly used in real applications, not just
popular in Genomic but in a lot of other areas as well. It is not only a way to visualize data, 
but also enhances the representation of scientific results into a level of aesthetics. Therefore, most people call figures with circular layout as `circos plot'.
Here the \textbf{circlize} package \footnote{It would be great if you can cite: Gu Z {\it et. al.} (2014) circlize implements and enhances circular visualization in R. {\it Bioinformatics}.}  aims to implement \textbf{Circos} in R. One important advantage for the implementation in R is that R is an ideal
environment which provides seamless connection between data analysis and data visualization. This package is not a front-end wrapper
to generate configuration files for \textbf{Circos}, but completely coded in R style by using R's elegant statistical and graphic engine.  
We aim to keep the flexibility and configurability of \textbf{Circos}, also make the package more straightforward to use and enhance it to support more types of graphics. 

\section{Principle of design}
Since most of the figures are composed of simple graphics, such as points, lines, polygon (for filled colors) {\it et al},
\textbf{circlize} implements low-level graphic functions for adding graphics in circular layout, so that more higher level
graphics can be easily comprised by low-level graphics. This principle ensures the generality 
that types of high-level graphics are not restricted by the software but determined by users.

Currently there are following graphic functions that can be used for plotting, they are similar to the functions without ``{\tt circos.}''
prefix from the traditional graphic engine (you can also see the correspondence in figure \ref{fig:circlize_correspondence}):

<<circlize_correspondence, echo = FALSE, fig.cap = "Correspondence between graphic functions in \\textbf{circlize} and in traditional R graphic engine.">>=
source("src/intro-00-correspondence.R")
@

\begin{itemize}
  \item {\tt circos.points}: add points in a cell, similar as {\tt points}.
  \item {\tt circos.lines}: add lines in a cell, similar as {\tt lines}.
  \item {\tt circos.rect}: add rectangle in a cell, similar as {\tt rect}.
  \item {\tt circos.polygon}: add polygon in a cell, similar as {\tt polygon}.
  \item {\tt circos.text}: add text in a cell, similar as {\tt text}.
  \item {\tt circos.axis}: add axis in a cell, functionally similar as {\tt axis} but with more features.
  \item {\tt circos.link}: this maybe the unique feature for circular layout to represent relationships between elements.
\end{itemize}

For adding points, lines and text in cells through the whole track (among several sectors), the following functions are available:

\begin{itemize}
  \item {\tt circos.trackPoints}: this can be replaced by {\tt circos.points} through a {\tt for} loop.
  \item {\tt circos.trackLines}: this can be replaced by {\tt circos.lines} through a {\tt for} loop.
  \item {\tt circos.trackText}: this can be replaced by {\tt circos.text} through a {\tt for} loop.
\end{itemize}

Functions to arrange the circular layout:

\begin{itemize}
  \item {\tt circos.trackPlotRegion}: create plotting regions for cells in a track.
  \item {\tt circos.updatePlotRegion}: update an existed cell.
  \item {\tt circos.par}: graphic parameters.
  \item {\tt circos.info}: print general parameters of current circos plot.
  \item {\tt circos.clear}: reset graphic parameters and internal variables.
\end{itemize}

Theoretically, you are able to draw most kinds of circos figures by the above functions. 
As you will see, all the figures which are `round' in the six vignettes are all 
generated by \textbf{circlize} package.

The following part of this vignette is structured as follows: First there is an example
to give a quick glance of how to implement a circular layout by \textbf{circlize}. Then we introduce the basic principle
(or the order of using the circos functions) for plotting. After that there are detailed explanations
of graphic parameters, coordinates transformation and usage of low-level functions. Finally we introduce some tricks
for making more complicated circos plots.

\section{A quick glance}
Following is an example to show the basic feature and usage of \textbf{circlize} package. 
First let's generate some random data. There needs a factor to represent categories,
values on x-axis, and values on y-axis.

<<>>=
set.seed(999)
n = 1000
a = data.frame(factor = sample(letters[1:8], n, replace = TRUE),
    x = rnorm(n), y = runif(n))
@

First initialize the layout. In this step, {\tt circos.initialize} allocates sectors in
the circle according to ranges of x-values in different categories. E.g,
if there are two categories, range for x-values in the first category is {\tt c(0, 2)}
and range for x-values in the second category is {\tt c(0, 1)}, the first category
would hold approximately $67\%$ areas of the circle.
Here we only need x-values because all cells in a sector share the same
x-ranges.

We explicitly set {\tt par(mar)} because the default graphic device has equal
values of width and height, we set the figure margins to a same value to make sure the plot
that we make is a real circle. 

<<circlize_glance_0, eval = FALSE>>=
library(circlize)
par(mar = c(1, 1, 1, 1), lwd = 0.1, cex = 0.7)
circos.par("track.height" = 0.1)
circos.initialize(factors = a$factor, x = a$x)
@

Draw the first track (figure \ref{fig:circlize_glance} A). Before drawing any track 
we need to know that all tracks should firstly be created by {\tt circos.trackPlotRegion}, then
those low-level functions can be applied (recall in traditional R graphic engine, 
you need first call {\tt plot.default} and then you can use functions such as {\tt points} and {\tt lines} to add graphics on it).
Since x-lims for cells in the track have already been defined in the initialization step, 
here we only need to specify the y-lim for each cell, either by {\tt y}
or {\tt ylim} argument. 

We also add axes in the first track, The axis for each cell is added by {\tt panel.fun} argument. 
{\tt circos.trackPlotRegion} creates plotting region cell by cell and the {\tt panel.fun}
is actually executed immediately after the creation of the plotting region for a certain cell. So {\tt panel.fun} actually means
adding graphics in the ``current cell''. After that, we add points
through the whole track by {\tt circos.trackPoints}. Finally, add two texts in a certain cell
(the cell is specified by {\tt sector.index} and {\tt track.index} argument). When adding the second
text, we do not specify {\tt track.index} because the package knows we are now in the first track.

Here what should be noted is that the first track has a index number of 1.
An internal variable which traces the tracks would set the `current track index' to 1. So if the track
index is not specified in the plotting functions such as {\tt circos.trackPoints} and {\tt circos.text}
which are called after the creation of the track, the current track index would be used as the default track index.
 (Details will be explained in the following sections).

<<circlize_glance_1, eval=FALSE>>=
circos.trackPlotRegion(factors = a$factor, y = a$y,
    panel.fun = function(x, y) {
        circos.axis()
})
col = rep(c("#FF0000", "#00FF00"), 4)
circos.trackPoints(a$factor, a$x, a$y, col = col, pch = 16, cex = 0.5)
circos.text(-1, 0.5, "left", sector.index = "a", track.index = 1)
circos.text(1, 0.5, "right", sector.index = "a")
@

Draw the second track (figure \ref{fig:circlize_glance} B).We use {\tt circos.trackHist} to add histograms in the track. The function
also creates a new track because drawing histogram is really high level, so we do not need to call {\tt circos.trackPlotRegion} here. 
The index for this track is 2.

<<circlize_glance_2, eval=FALSE>>=
bgcol = rep(c("#EFEFEF", "#CCCCCC"), 4)
circos.trackHist(a$factor, a$x, bg.col = bgcol, col = NA)
@

Draw the third track (figure \ref{fig:circlize_glance} C). Here some meta data for the current cell can be obtained by {\tt get.cell.meta.data}. This function needs
{\tt sector.index} and {\tt track.index} arguments, and if they are not specified, it means
it is the current sector index and the current track index.

<<circlize_glance_3, eval=FALSE>>=
circos.trackPlotRegion(factors = a$factor, x = a$x, y = a$y,
    panel.fun = function(x, y) {
        grey = c("#FFFFFF", "#CCCCCC", "#999999")
        sector.index = get.cell.meta.data("sector.index")
        xlim = get.cell.meta.data("xlim")
        ylim = get.cell.meta.data("ylim")
        circos.text(mean(xlim), mean(ylim), sector.index)
        circos.points(x[1:10], y[1:10], col = "red", pch = 16, cex = 0.6)
        circos.points(x[11:20], y[11:20], col = "blue", cex = 0.6)
})
@

You can update an existed cell by specifying {\tt sector.index} and {\tt track.index} in {\tt circos.updatePlotRegion}.
The function erases graphics which have been added. Here we erase graphics in one cell in track 2, sector {\tt d}
and re-add some points (figure \ref{fig:circlize_glance} D). {\tt circos.updatePlotRegion} can not modify the {\tt xlim}
and {\tt ylim} of the cell as well as other settings related to the position of the cell. {\tt circos.updatePlotRegion}
will modify current sector index and track index.

<<circlize_glance_3_update, eval=FALSE>>=
circos.updatePlotRegion(sector.index = "d", track.index = 2)
circos.points(x = -2:2, y = rep(0, 5))
xlim = get.cell.meta.data("xlim")
ylim = get.cell.meta.data("ylim")
circos.text(mean(xlim), mean(ylim), "updated")
@

Draw the fourth track (figure \ref{fig:circlize_glance} E). Here you can choose different 
line types which is similar as {\tt type} argument in {\tt lines}.

<<circlize_glance_4, eval=FALSE>>=
circos.trackPlotRegion(factors = a$factor, y = a$y)
circos.trackLines(a$factor[1:100], a$x[1:100], a$y[1:100], type = "h")
@

Draw links (figure \ref{fig:circlize_glance} F). Links can be from point to point, point to interval or interval to interval.
Some of the arguments will be explained in the following sections.

<<circlize_glance_5, eval=FALSE>>=
circos.link("a", 0, "b", 0, h = 0.4)
circos.link("c", c(-0.5, 0.5), "d", c(-0.5,0.5), col = "red",
    border = "blue", h = 0.2)
circos.link("e", 0, "g", c(-1,1), col = "green", lwd = 2, lty = 2)
@


<<circlize_glance, echo = FALSE, out.width = "0.6\\textheight", out.height = "0.9\\textheight", fig.width = 7, fig.height = 10.5, fig.cap = "A step-by-step example by \\textbf{circlize}.">>=
par(mfrow = c(3, 2), mar = c(1, 1, 1, 1))

<<circlize_glance_0>>
<<circlize_glance_1>>
circos.clear()
text(-0.9, 0.9, "A", cex = 1.5)

<<circlize_glance_0>>
<<circlize_glance_1>>
<<circlize_glance_2>>
circos.clear()
text(-0.9, 0.9, "B", cex = 1.5)

<<circlize_glance_0>>
<<circlize_glance_1>>
<<circlize_glance_2>>
<<circlize_glance_3>>
circos.clear()
text(-0.9, 0.9, "C", cex = 1.5)

<<circlize_glance_0>>
<<circlize_glance_1>>
<<circlize_glance_2>>
<<circlize_glance_3>>
<<circlize_glance_3_update>>
circos.clear()
text(-0.9, 0.9, "D", cex = 1.5)

<<circlize_glance_0>>
<<circlize_glance_1>>
<<circlize_glance_2>>
<<circlize_glance_3>>
<<circlize_glance_3_update>>
<<circlize_glance_4>>
circos.clear()
text(-0.9, 0.9, "E", cex = 1.5)

<<circlize_glance_0>>
<<circlize_glance_1>>
<<circlize_glance_2>>
<<circlize_glance_3>>
<<circlize_glance_3_update>>
<<circlize_glance_4>>
<<circlize_glance_5>>
circos.clear()
text(-0.9, 0.9, "F", cex = 1.5)
par(mfrow = c(1, 1))
@

You can get a summary of your circular layout by {\tt circos.info}.

<<eval = FALSE>>=
circos.info()
circos.info(sector.index = "a", track.index = 2)
@

Finally we need to reset the graphic parameters and internal variables, so that it will not mess up your next plot.

<<eval=FALSE>>=
circos.clear()
@

\section{Details}
In this section, more details of the package are explained.

\subsection{Coordinate transformation}

There is a {\bf data coordinate} in which the range for x-axis and y-axis is the range of data,
a {\bf polar coordinate} to allocates graphics on the circle and a {\bf canvas coordinate} which really
draws the graphics to the device (figure \ref{fig:circlize_coordinate_transformation}). 
Since a circos plot is composed by cells which are intersection of sectors and tracks,
each cell has its own data coordinate. The package first transforms from the data
coordinate to a polar coordinate and finally transforms into the canvas coordinate.

<<circlize_coordinate_transformation, echo = FALSE, out.width = "0.3546099\\textheight", out.height = "0.8\\textheight", fig.width = 5, fig.height = 11.28, fig.cap = "Transformation between different coordinates. Top: data coordinate; Middle: polar coordinate; Bottom: canvas coordinate.">>=
source("src/intro-03-transformation.R")
@

The final canvas coordinate is in fact an ordinary coordinate in R plotting system with
x-range from -1 to 1 and y-range from -1 to 1 by default.

{\it {\bf It should be noted that the circular layout is always (or mostly except you want to draw something out of the circle) 
drawn inside the circle which has radius of 1 (unit circle), from outside to inside. } }

For users, they only need to imagine that each cell is a normal rectangular plotting region (data coordinate) in
which x-lim and y-lim are ranges of data in the category respectively. \textbf{circlize}
knows which cell you are in and does all the transformations automatically.


\subsection{Rules for making circular layout}

The rules for making circular layout is rather simple. It follows the sequence of
``initialize - create track - add graphics - create track - add graphics - ... - clear'' (figure \ref{fig:circlize_order}).
Details are as follows:

<<circlize_order, echo = FALSE, out.width = "\\textwidth", out.height = "0.8571429\\textwidth", fig.height = 6, fig.width = 7, fig.cap = "Order of drawing circular layout.">>=
source("src/intro-02-order.R")
@

\begin{enumerate}
  \item Initialize the layout using {\tt circos.initialize}. Since circular layout in fact visualizes data which is in categories,
        there should be a factor and a x-range variable to allocate categories into sectors.
  \item Create plotting regions for the new track and add graphics. The new track is created just inside
        the previously created one and the index of the track is added by 1. Only after the creation of the track can you
        add other graphics on it. There are three ways to add graphics in cells.
        \begin{enumerate}
            \item After the creation of the track, use low-level graphic function like {\tt circos.points},
                  {\tt circos.lines}, ... to add graphics cell by cell. It always involves
                  a {\tt for} loop.
            \item Use {\tt circis.trackPoints}, {\tt circos.trackLines}, ... to add graphics 
                  through all cells simultaneously. However, it is not recommended because
                  it would make you a little confused and also it cannot make complicated graphics.
            \item Use {\tt panel.fun} argument in {\tt circos.trackPlotRegion} to add
                  graphics immediately after the creation of a certain cell. {\tt panel.fun} needs
                  two arguments {\tt x} and {\tt y} which are x-values and y-values that are
                  in the current category. This subset operation is applied automatically.
                  This is the most recommended way.
        \end{enumerate}
        
        Plotting regions for cells which have already been created can be updated by {\tt circos.updatePlotRegion}.
        {\tt circos.updatePlotRegion} will erase everything that you added before.
        
        Low level functions such as {\tt circos.points} can be applied to any created cell by specifying
        {\tt sector.index} and {\tt track.index}.
  \item Repeat step 2 to add more tracks on the circle unless it reaches the center of the circle.
  \item Call {\tt circos.clear} to do cleaning.
\end{enumerate}

As mentioned above, there are three ways to add graphics on the created track. 

1. create plotting regions for the whole track
and then add graphics by specifying {\tt sector.index} and {\tt track.index}. In the following pseudo code, {\tt x1}, {\tt y1}
are data points in a given cell, which means you need to do data subsetting by yourself.

<<eval = FALSE>>=
circos.initialize(factors, xlim)
circos.trackPlotRegion(factors, ylim)
for(sector.index in all.sector.index) {
    circos.points(x1, y1, sector.index)
    circos.lines(x2, y2, sector.index)
}
@

2. add graphics through a batch mode. This can be replaced by {\tt circos.points} or {\tt circos.lines} in a {\tt for} loop.
In the following code, you need to specifying the {\tt factors} and now {\tt x} and {\tt y} are data points for all categories.
The data points for a given cell will be subsetted according {\tt factors}.

<<eval = FALSE>>=
circos.initialize(factors, xlim)
circos.trackPlotRegion(factors, ylim)
circos.trackPoints(factors, x, y)
circos.trackLines(factors, x, y)
@

3. use a panel function to add self-defined graphics as soon as the cell has been created. This is the way recommended since when
you look at {\tt panel.fun}, it is just like adding graphics in traditional R graphics system. There will be a more detailed explanation
of {\tt panel.fun} argument in the following sections.

<<eval = FALSE>>=
circos.initialize(factors, xlim)
circos.trackPlotRegion(factors, all_x, all_y, ylim,
    panel.fun = function(x, y) {
        circos.points(x, y)
        circos.lines(x, y)
})
@

There is several internal variables keeping tracing of the current sector and track when applying {\tt circos.trackPlotRegion} and {\tt circos.updatePlotRegion}.
So although functions like {\tt circos.points}, {\tt circos.lines} need to specify the index of sector and track,
they will take the current one by default. As a result,
if you draw points, lines, text {\it et al} just after the creation of the track or cell, you do not need to set the sector
index and the track index explicitly and it will be put in the most recently created cell. Note again, only {\tt circos.trackPlotRegion}
and {\tt circos.updatePlotRegion} can reset the current track index and sector index.

Finally, in \textbf{circlize} package, function with prefix ``{\tt circos.track}'' would affect all cells in one track.

\subsection{Sectors and tracks}

A circular layout is composed of sectors and tracks, as illustrated in figure \ref{fig:circlize_coordinate}.
The red circle is the track and the blue one is the sector. The intersection of a sector and 
a track is called a cell which can be thought as an imaginary plotting region for data points in a certain category ({\bf data coordinate}). 

<<circlize_coordinate, echo = FALSE, out.width = "0.8\\textwidth", fig.cap = "Sectors and tracks in circular layout. There are 10 sectors and 4 tracks. Orders of sectors are randomly permuted.">>=
source("src/intro-04-coordinate.R")
@

Sectors are first allocated on the circle and determined by {\tt circos.initialize}, then track allocation is determined by {\tt circos.trackPlotRegion}.
{\tt circos.initialize} needs a category variable and data value which implicates the range of data in each category. The range
of data can be specified either by {\tt x} or {\tt xlim}.

<<eval = FALSE>>=
circos.initialize(factors, x)
circos.initialize(factors, xlim)
@

There are something very important that should be noted in the initialization step. In this step, not only the width
of each sector is assigned, but also the order of sectors on the circle is determined. 
{\bf Order of the sectors are determined by the order of levels of the factor}. So if you want to change the order
of the sectors, just change of the level of {\tt factors} variable. The following codes would generate different figures (figure \ref{fig:circlize_factor}):

<<eval = FALSE>>=
fa = c("d", "f", "e", "c", "g", "b", "a")
f1 = factor(fa)
circos.initialize(factors = f1, xlim = c(0, 1))
f2 = factor(fa, levels = fa)
circos.initialize(factors = f2, xlim = c(0, 1))
@

<<circlize_factor, echo = FALSE, out.width = "\\textwidth", out.height = "0.5\\textwidth", fig.width = 10, fig.height = 5, fig.cap = "Different sector orders.">>=
source("src/intro-05-factor.R")
@

If {\tt x} which is the x-values corresponding
to {\tt factors} is specified, the range for x-values in different categories will be calculated according to {\tt factors}
automatically. And if {\tt xlim} is specified, it should be either a matrix which has same number of rows as the length
of the {\tt factors} levels or a two-element vector. If it is a two-element vector, it would be extended to a matrix which 
has the same number of rows as the length of {\tt factors} levels. Here, every row in {\tt xlim} corresponds to the x-ranges
of a category and the order of rows in {\tt xlim} corresponds to the order of levels of {\tt factors}.

{\bf Since all cells in one sector and in different tracks share the same x-ranges}, for each track, we only need to specify the y-ranges
for cells. Similar as {\tt circos.initialize}, {\tt circos.trackPlotRegion} can also receive either {\tt y} or {\tt ylim} argument
to specify the range of y-values. There is also a {\tt force.ylim} argument to specify whether all cells in one same track should
share the same y-ranges. {\tt force.ylim} is only used along with {\tt y}.

<<eval = FALSE>>=
circos.trackPlotRegion(factors, y)
circos.trackPlotRegion(factors, ylim)
@

In the track creation step, since all sectors are already allocated in the circle, if {\tt factors} argument is not set, 
{\tt circos.trackPlotRegion} would create plotting regions for all available sectors. Also, levels of {\tt factors} do not
need to be specified explicitly because the order of sectors has already be determined in the initialization step. 
If users only create cells for part of sectors in the track (not all sectors), in fact, cells in remaining
unspecified sectors are created as well, but with no borders (pretending they are not created).

Cells are basic units in the circle and are independent with each other. After the creation of cells, they have self-contained meta values
of x-lim and y-lim (data range measured in data coordinate). So if you are adding graphics in one cell, you do not need to consider things outside the cell and also you
do not need to consider you are in the circle. Just pretending it is rectangle area. 


<<circlize_region, echo = FALSE, out.width = "0.8\\textwidth", fig.cap = "Regions in a cell">>=
source("src/intro-06-region.R")
@

<<circlize_direction, echo = FALSE, out.width = "\\textwidth", out.height = "0.5\\textwidth", fig.width = 10, fig.height = 5, fig.cap = "Sector directions. Sector orders are {\\tt a, b, ..., h}.">>=
source("src/intro-07-direction.R")
@

\subsection{Graphic parameters}
Some basic parameters for the circular layout can be set through {\tt circos.par}. The parameters
are as follows, note some parameters can only be assigned before the initialization of the circular layout.

\begin{itemize}
    \item {\tt start.degree}: The starting degree where to put the first sector. Note this degree is measured 
          in the standard polar coordinate which means it is always reverse clockwise. See figure \ref{fig:circlize_direction}.
    \item {\tt gap.degree}: Gap between two neighbour sectors. It can be a single value which means all gaps share same
          degree, or a vector which has same length as factors levels. {\bf The first gap is after the first sector.}
          See figure \ref{fig:circlize_direction} and figure \ref{fig:circlize_region}.
    \item {\tt track.margin}: Like {\tt margin} in Cascading Style Sheets (CSS), it is the blank area
          out of the plotting region, also outside of the borders. Since left and right margin are controlled
          by {\tt gap.degree}, only bottom and top margin need to be set. The value for the {\tt track.margin}
          is the percentage to the radius of the unit circle. See figure \ref{fig:circlize_region}.
    \item {\tt cell.padding}: Padding of the cell. Like {\tt padding} in Cascading Style Sheets
          (CSS), it is the blank area around the plotting regions, but within the borders.
          The parameter has four values, which control the bottom, left, top and right padding
          respectively. The first and the third padding
          values are the percentages to the radius of the unit circle, and the second and
          fourth values are the degrees. See figure \ref{fig:circlize_region}.
    \item {\tt unit.circle.segments}: Since curves are simulated by a series of straight lines,
          this parameter controls the amount of segments to represent a curve. The minimal length
          of the line segment is the length of the unit circle ({\tt 2*pi}) divided by {\tt unit.circle.segments}. 
          More segments means better approximation for the curves, while generate larger file size if figures are in PDF format.
    \item {\tt track.height}: The default height of tracks. It is the percentage to the radius
          of the unit circle. The height includes the top and bottom cell paddings but not the margins.
    \item {\tt points.overflow.warning}: Since each cell is in fact not a real plotting region but only
          an ordinary rectangle (or more precisely, rectangle-like), it does not remove points that are plotted outside of
          the region. So if some points are out of the plotting region, by default, the 
          package would continue drawing the points and print warnings. But in some 
          circumstances, draw something out of the plotting region is useful, such as adding
          some legend or text. Set this value to {\tt FALSE} to turn off the warnings.
    \item {\tt canvas.xlim}: The coordinate for the canvas. \textbf{circlize} is forced to put everything in side the unit circle, so
          {\tt xlim} and {\tt ylim} for the canvas would be {\tt c(-1, 1)} by default. However, you can set it to a more broad
          interval if you want to draw other things out of the circle. By choose proper
          {\tt canvas.xlim} and {\tt canvas.ylim}, you can only draw part of the circle. E.g. setting
          {\tt canvas.xlim} to {\tt c(0, 1)} and {\tt canvas.ylim} to {\tt c(0, 1)} would only draw
          circle in the region of {\tt (0, pi/2)}. 
    \item {\tt canvas.ylim}: The coordinate for the canvas.
    \item {\tt clock.wise}: The order of drawing sectors. Default is {\tt TRUE} which means clockwise (figure \ref{fig:circlize_direction}).
          {\bf But note that inside each cell, the direction of x-axis is always clockwise and direction of y-axis is always from inside to outside in the circle.}
\end{itemize}

Default values for graphic parameters are in table \ref{table:gp}.

\begin{table}[ht]
\centering
\begin{tabular}{ll}
  \hline
parameter & default value \\ 
  \hline
{\tt start.degree} &     {\tt 0} \\ 
{\tt gap.degree} &    {\tt 1} \\ 
{\tt track.margin} &    {\tt c(0.01, 0.01)} \\ 
{\tt cell.padding} &    {\tt c(0.02, 1.00, 0.02, 1.00)} \\ 
{\tt unit.circle.segments} &    {\tt 500} \\ 
{\tt track.height} &    {\tt 0.2 } \\ 
{\tt points.overflow.warning} &    {\tt TRUE} \\ 
{\tt canvas.xlim} &    {\tt c(-1, 1)} \\ 
{\tt canvas.ylim} &    {\tt c(-1, 1)} \\ 
{\tt clock.wise} &    {\tt TRUE} \\ 
   \hline
\end{tabular}
\caption{Default graphic parameters}
\label{table:gp}
\end{table}

Parameters related to the allocation of sectors cannot be changed after the initialization of the circular layout.
So {\tt start.degree}, {\tt gap.degree}, {\tt canvas.xlim}, {\tt canvas.ylim} and {\tt clock.wise} can only
be modified before {\tt circos.initialize}. The second and the fourth element of {\tt cell.padding} (left and right paddings) can not
be modified either (or will be ignored).

\subsection{Create plotting region}

As described above, only after creating the plotting region can you add low-level graphics on it. The minimal set
of arguments for this function is to set either {\tt y} or {\tt ylim} which assigns range of y-values for the
track. {\tt circos.trackPlotRegion} create tracks for all sectors although in some case only parts of them are visible.

If {\tt factors} is not specified, all cells in the track will be created with the same settings.
If {\tt factors}, {\tt x} and {\tt y} are set, they need to be vectors with the same length. 
Proper values of {\tt x} and {\tt y} that correspond to current cell will be passed to {\tt panel.fun}
by subsetting {\tt factors} internally.

Graphic arguments such as {\tt bg.border} and {\tt bg.col}
can either be a scalar or a vector. If it is a vector, the length must be equal to the length of {\tt factors} levels
and the order should also correspond to the order of {\tt factors} levels. Thus you can create plot regions 
with different styles of borders and background colors. 

If you are confused with the {\tt factors} orders, you can also
customize the borders and background colors inside {\tt panel.fun}. {\tt get.cell.meta.data("cell.xlim")}
and {\tt get.cell.meta.data("cell.ylim")} give you positions of the plotting region and you can customize
plot regions by {\tt circos.rect}.

\subsection{Update plotting region}

If {\tt track.index} is specified in {\tt circos.trackPlotRegion} and the specified track is already created,
the track will be updated with new graphics. In this case, settings related to the positions of the track such as the height of the track
can not be modified.

<<eval = FALSE>>=
circos.trackPlotRegion(data, ylim = c(0, 1), track.index = 1, ...)
@

For single cell, {\tt circos.updatePlotRegion} can be used to erase all graphics that have been already plotted in the cell.
In this case, you cannot re-define y-ranges in the cell either.

<<eval = FALSE>>=
circos.updatePlotRegion(sector.index, track.index)
circos.points(x, y, sector.index, track.index)
@

\subsection{Points}
Adding points by {\tt circos.points} is similar as {\tt points} function. Possible usage is:

<<eval = FALSE>>=
circos.points(x, y)
circos.points(x, y, sector.index, track.index)
circos.points(x, y, pch, col, cex)
@

Since {\tt circos.points} is a low-level function, it can only be applied to
cells which have been already created. If {\tt sector.index} or {\tt track.index} is not
specified, it uses `current' index for sector and track which are
defined by the most recent {\tt circos.trackPlotRegion} or {\tt circos.updatePlotRegion}.

{\tt circos.trackPoints} can add points in the whole cells on a same track as a batch.
It is the same as if you use {\tt circos.points} in a {\tt for} loop.


\subsection{Lines}
Parameters for adding lines by {\tt circos.lines} are similar to {\tt lines} function, 
as illustrated in figure \ref{fig:circlize_lines}. One additional feature is that the areas under/above lines can be 
specified by {\tt area} argument which can help to identify the direction of y-axes. Also the base line for the area can be set by {\tt baseline}.
{\tt baseline} can be pre-defined string of {\tt bottom} or {\tt top}, or numeric values. {\tt baseline} is also workable
when {\tt lty} is set to {\tt h}.

<<circlize_lines, echo = FALSE, out.width = "0.8\\textwidth", fig.cap = "Line styles">>=
source("src/intro-08-lines.R")
@

Straight lines are transformed to curves when mapping to circular layout (figure \ref{fig:circlize_linecurve}). Normally, 
curves can be approximated by a series of segments of straight lines. With more segments,
there would be better approximation, but with larger size if you generate figures into PDF files, especially
for huge genomic data. Default number of segments in \textbf{circlize} is a balance between
the quality and size of the figure. Still you can change the number of segments by {\tt circos.par("unit.circle.segments")}.
The length of minimal segment is the length of the unit circle (2$\pi$) divided by 
{\tt circos.par("unit.circle.segments")}. When you plot radical line, you can set {\tt straight} argument to {\tt TRUE}
to get rid of unnecessary segmentation. 

<<circlize_linecurve, echo = FALSE, out.width = "0.8\\textwidth", fig.cap = "Straight lines will be transformed into curves in the circle.">>=
source("src/intro-08-linescurve.R")
@

Possible usage for {\tt circos.lines} is:

<<eval = FALSE>>=
circos.lines(x, y)
circos.lines(x, y, sector.index, track.index)
circos.lines(x, y, col, lwd, lty, type, straight)
circos.lines(x, y, col, area, baseline, border)
@

Similar as {\tt circos.points}, if no {\tt sector.index} or {\tt track.index} is
specified, `current' index would be used. Also, there is a {\tt circos.trackLines}
which is identical to {\tt circos.lines} in a {\tt for} loop.

\subsection{Text}
Only the facing of text by {\tt circos.text} should be noted, as illustrated in figure \ref{fig:circlize_text}.
{\tt srt} in {\tt text} has been degenerated as {\tt facing} in {\tt circos.text} which  
support eight types of rotation that are pre-defined in ({\tt inside}, {\tt outside}, {\tt reverse.clockwise}, 
{\tt clockwise}, {\tt downward}, {\tt bending.inside}, {\tt bending.outside}).
But {\tt adj} argument is still applicable in {\tt circos.text}. Please note for {\tt bending.inside}
and {\tt bending.outside}, currently, single line text is only supported.
Possible usage for {\tt circos.text} is:

<<circlize_text, echo = FALSE, out.width = "0.8\\textwidth", fig.cap = "Text facing.">>=
source("src/intro-09-text.R")
@

<<eval = FALSE>>=
circos.text(x, y, labels)
circos.text(x, y, labels, sector.index, track.index)
circos.text(x, y, labels, facing, adj, cex, col, font)
@

In some case, we may want to set the text facing more human-easy. For example, we want the text facing
clockwise in right half of the circle while reverse-closewise in the left half of the circle. This can be easily done by 
setting {\tt niceFacing} to {\tt TRUE}. This option only works for {\tt facing} value of {\tt inside},
{\tt outside}, {\tt clockwise}, {\tt reverse.clockwise}, {\tt bending.inside} and {\tt bending.outside}. When {\tt niceFacing} is on, values for internal {\tt facing}
and {\tt adj} will be re-defined according to the position of the texts in the circle.
Please refer to figure \ref{fig:circlize_text_easy} for examples.

<<circlize_text_easy, echo = FALSE, out.width = "0.6\\textheight", out.height = "0.9\\textheight", fig.width = 6, fig.height = 9, fig.cap = "Human easy text facing. When {\\tt niceFacing} is on, settings in the same row are actually identical. Red dots represent positions of the texts.">>=
source("src/intro-09-text-niceFacing.R")
@

There is also a {\tt circos.trackText} in the package.

\subsection{Rectangle}
If you imagine the plotting region in a cell as Cartesian coordinate, then {\tt circos.rect} draws rectangles.
In the circle, the up and bottom edge become two arcs. This function can be vectorized.

<<eval = FALSE>>=
circos.rect(xleft, ybottom, xright, ytop)
circos.rect(xleft, ybottom, xright, ytop, sector.index, track.index)
circos.rect(xleft, ybottom, xright, ytop, col, border, lty, lwd)
@

\subsection{Polygon}
Similar as {\tt circos.rect} and {\tt polygon}, {\tt circos.polygon} draws a polygon through a series
of points in a cell:

<<eval = FALSE>>=
circos.polygon(x, y)
circos.polygon(x, y, sector.index, track.index)
circos.polygon(x, y, col, border, lty, lwd)
@

In figure \ref{fig:circlize_errorline}, the area of standard deviation of the smoothed line
is drawn by {\tt circos.polygon}. (Source code is in {\it Examples} section of {\tt circos.polygon}
help page.)

<<circlize_errorline, echo = FALSE, out.width = "0.8\\textwidth", fig.cap = "Area of standard deviation of the smoothed line.">>=
source("src/intro-10-smooth.R")
@

\subsection{Axis}
Because there may be no space to put y-axis, only adding x-axis for each cell is supported by {\tt circos.axis}, as illustrated in figure \ref{fig:circlize_axis}.
A lot of styles for axis can be set such as the position and length of major ticks, the number of minor ticks,
the position and direction of the axis labels and the position of the x-axis. 

In figure \ref{fig:circlize_axis}, axis styles in different sectors are :

<<circlize_axis, echo = FALSE, out.width = "0.6\\textwidth", out.height = "1.2\\textwidth", fig.width = 6, fig.height = 12, fig.cap = "Axes">>=
source("src/intro-11-axis.R")
@

\begin{itemize}
  \item a: Major ticks are calculated automatically, other settings are default.
  \item b: Ticks are pointing to inside of the circle, facing of tick labels is set to {\tt outside}.
  \item c: Position of x-axis is {\tt bottom} of the cell.
  \item d: Ticks are pointing to inside of the circle, facing of tick labels is set to {\tt reverse.clockwise}.
  \item e: Self-defined major ticks.
  \item f: Self-defined major ticks and tick labels, no minor ticks.
  \item g: No ticks for both major and minor ones, facing of tick labels is set to {\tt reverse.clockwise}.
  \item h: Number of minor ticks between two major ticks is set to 2. Length of ticks is longer and axis labels are more away from ticks. Facing of tick labels is set to {\tt clockwise}.
\end{itemize}

The facing of labels text can also be optimized by {\tt labels.niceFacing} (by default it is {\tt TRUE}).

For {\tt circos.axis}, possible usage is as follows. {\tt h} can be pre-defined string of {\tt bottom} or {\tt top}, or numeric values. 

<<eval = FALSE>>=
circos.axis(h)
circos.axis(h, sector.index, track.index)
circos.axis(h, major.at, labels, major.tick)
circos.axis(h, major.at, labels, major.tick, labels.font, labels.cex,
            labels.facing, labels.away.percentage)
circos.axis(h, major.at, labels, major.tick, minor.ticks,
            major.tick.percentage, lwd)
@

Y-axis is also supported (figure \ref{fig:circlize_axis}), but you need to set {\tt gap.degree} in {\tt circos.par} 
to make sure there are enough spaces for y-axes.

<<eval = FALSE>>=
circos.yaxis(side)
circos.yaxis(at, labels, sector.index, track.index)
@

\subsection{Links}
{\tt circos.link} draws links from points and intervals (figure \ref{fig:circlize_link} A). 
If both ends are single points, the link is represented as a line. If one of the ends is 
an interval, the link would be a belt/ribbon. Links do not hold any position as tracks,
so they can be overlapping with tracks.

Possible usage for {\tt circos.link} is:

<<eval = FALSE>>=
circos.link(sector.index1, 0, sector.index2, 0)
circos.link(sector.index1, c(0, 1), sector.index2, 0)
circos.link(sector.index1, c(0, 1), sector.index2, c(1, 2))
circos.link(sector.index1, c(0, 1), sector.index2, 0, col, lwd, lty, border)
@


<<circlize_link, echo = FALSE, out.width = "0.6\\textheight", out.height = "0.9\\textheight", fig.width = 6, fig.height = 9, fig.cap = "A) set different positions of roots; B) set different height of two borders. C,D) set different {\\tt h} and {\\tt w}. E) if two branches overlap, the link will be degenerated as a 'hill'. F) links with directions.">>=
source("src/intro-12-link.R")
@

The position of link `root' is controlled by {\tt rou}. By default, it is the end position of the most recently created track.
So normally, you don't need to care about this setting. The default value of {\tt rou} is calculated by an interval function {\tt get\_most\_inside\_radius()}:

<<tidy = TRUE>>=
circlize:::get_most_inside_radius
@

By default, the two roots of the link are located in a same circle. The positions of two 
roots can be assigned with different values by {\tt rou1} and {\tt rou2} (figure \ref{fig:circlize_link} B).

<<eval = FALSE>>=
circos.link(sector.index1, 0, sector.index2, 0, rou)
circos.link(sector.index1, 0, sector.index2, 0, rou1, rou2)
@

The height of the link can be controlled by {\tt h} argument in {\tt circos.link}.

When the link represents as a ribbon (i.e. link from point to interval or from interval to interval),
It can not ensure that one border is always below or above the other. Which means, in 
some case, the two borders are intersected and the link would be messed up. It happens
especially when position of the two ends are too close or the width of one end is extremely large while
the width of the other end is too small. In that case, users can manually set height of the top
and bottom border by {\tt h} and {\tt h2} (figure \ref{fig:circlize_link} C).

<<eval = FALSE>>=
circos.link(sector.index1, 0, sector.index2, 0, h)
circos.link(sector.index1, 0, sector.index2, 0, h, h2)
@

The border of link is in fact a quadratic Bezier curve, so you can control the shape of the 
link by {\tt w} and {\tt w2} ({\tt w2} controls the shape of bottom border, figure \ref{fig:circlize_link} D).
For more explanation of {\tt w}, please refer to \url{http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Rational_B.C3.A9zier_curves}.

<<eval = FALSE>>=
circos.link(sector.index1, 0, sector.index2, 0, w)
circos.link(sector.index1, 0, sector.index2, 0, w, w2)
@

If two branches overlap, the link will be de-generated as a 'hill' (figure \ref{fig:circlize_link}, E).
Also, links can have arrows to identify the directions (figure \ref{fig:circlize_link}, F). For adding
arrows, the {\tt directional} argument with value 0 means there is no direction, 1 means the direction 
is from point1 to point2 and -1 means the direction is from point2 to point1. If the link
represents as a belt, a line with arrow will be added in the center of the link to represent directions.

<<eval = FALSE>>=
circos.link(sector.index1, 0, sector.index2, 0, directional = 1)
circos.link(sector.index1, c(0, 1), sector.index2, c(0, 1), directional = -1)
@

\subsection{The {\tt panel.fun} argument in {\tt circos.trackPlotRegion}}

{\tt panel.fun} argument in {\tt circos.trackPlotRegion} is useful to apply plotting as soon as the cell has been created. This self-defined
function needs two arguments {\tt x} and {\tt y} which are data points that belong to this cell. The value for such values are automatically extracted from {\tt x} and {\tt y}
in {\tt circos.trackPlotRegion} according to the category argument {\tt factors}. In the following example, inside {\tt panel.fun},
for category {\tt a}, {\tt x} would be {\tt 1:3} and {\tt y} are {\tt 5:3}. If {\tt x} or {\tt y} in {\tt circos.trackPlotRegion} is {\tt NULL}, then {\tt x} or {\tt y} inside
{\tt panel.fun} is also {\tt NULL}.

<<eval = FALSE>>=
factors = c("a", "a", "a", "b", "b")
x = 1:5
y = 5:1
circos.trackPlotRegion(factors = factors, x = x, y = y,
    panel.fun = function(x, y) {
        circos.points(x, y)
})
@

In {\tt panel.fun}, one thing important is that if you use any low-level graphic functions, you don't need to specify {\tt sector.index} and {\tt track.index} explicitly.
Remember that when applying {\tt circos.trackPlotRegion}, cells in the track are created one after one. When a cell is created, \textbf{circlize} would set the sector index
and track index of the cell as the `current' index for the sector and track. When the cell is created, {\tt panel.fun} would be executed immediately. Without specifying
{\tt sector.index} and {\tt track.index}, the `current' one would be used and that's exactly what you need.

The advantage of {\tt panel.fun} is that it makes you feel you are using graphical functions 
in traditional graphic engine (You can see it is the same of using {\tt circos.points(x, y)} and {\tt points(x, y)}).
It will be much easier for users to understand and customize new graphics. 

Inside {\tt panel.fun}, more information of the `current' cell can be obtained through
{\tt get.cell.meta.data}. Also this function takes the `current' sector and `current' track by default,
Explanation of {\tt get.cell.meta.data} can be found in following section.


\subsection{High-level plotting functions}

With those low-level graphic functions such as {\tt circos.points}, {\tt circos.lines},
more high-level functions can be easily implemented. \textbf{circlize} provides a high-level 
function {\tt circos.trackHist} which draws histograms or the density
distributions of data (figure \ref{fig:circlize_hist}). Users can learn how to implement
high-level functions to support graphs such as barplot, heatmap, ... according to the source code of {\tt circos.trackHist}.
In {\tt circos.trackHist}, it first calls {\tt hist} or {\tt density} to calculate the distribution, then creates a new track,
finally uses {\tt circos.rect} or {\tt circos.lines} to draw histograms or density distributions.

In figure \ref{fig:circlize_hist}, the first track is histograms in which all the {\tt ylim} are the same.
The second track is histograms in which {\tt force.ylim} is {\tt FALSE}.
The third and the fourth tracks are density distributions in which y-lims
are forced same or not.

<<circlize_hist, echo = FALSE, out.width = "0.8\\textwidth", fig.cap = "Histograms in circular layout.">>=
source("src/intro-14-hist.R")
@

In figure \ref{fig:circlize_heatmap} there are heatmap and cluster dendrograms in circular layout. Heatmap is
series of grids which can be drawn by {\tt circos.rect}. Dendrograms are series of lines which can be drawn
by {\tt circos.lines}. Here we also have a high-level {\tt circos.dendrogram} function to draw the dendrograms. 

<<circlize_heatmap, echo = FALSE, out.width = "0.8\\textwidth", fig.cap = "Circular heatmap with dendrogram trees.">>=
source("src/intro-15-heatmap.R")
@

\subsection{Other functions}

{\tt get.cell.meta.data} can provide detailed information for a cell. It needs the index
of sector and track as arguments. As usual, it uses `current' index by default.

<<eval = FALSE>>=
get.cell.meta.data(name)
get.cell.meta.data(name, sector.index, track.index)
@

Items that can be extracted by {\tt get.cell.meta.data} are:

\begin{itemize}
  \item {\tt sector.index}: The name (label) for the sector.
  \item {\tt sector.numeric}.index: Numeric index for the sector. It is the numeric order of {\tt factors} levels in initialization step.
  \item {\tt track.index}: Numeric index for the track.
  \item {\tt xlim}: Minimal and maximal values on the x-axis.
  \item {\tt ylim}: Minimal and maximal values on the y-axis.
  \item {\tt xcenter}: mean of {\tt xlim}.
  \item {\tt ycenter}: mean of {\tt ylim}.
  \item {\tt xrange}: Range of {\tt xlim}.
  \item {\tt yrange}: Range of {\tt ylim}.
  \item {\tt cell.xlim}: Minimal and maximal values on the x-axis extended by cell paddings.
  \item {\tt cell.ylim}: Minimal and maximal values on the y-axis extended by cell paddings.
  \item {\tt xplot}: Degree of right and left borders in the plotting region.
                        The first element corresponds to the start point of values on x-axis ({\tt cell.xlm[1]})
                        and the second element corresponds to the end point of values on x-axis ({\tt cell.xlim[2]})
                        Since x-axis in data coordinate in cells are always clockwise, {\tt xplot[1]} is larger
                        than {\tt xplot[2]}.
  \item {\tt yplot}: Radius of bottom and top radius in the plotting region.
  \item {\tt cell.start.degree}: Same as {\tt xplot[1]}.
  \item {\tt cell.end.degree}: Same as {\tt xplot[2]}.
  \item {\tt cell.bottom.radius}: Same as {\tt yplot[1]}.
  \item {\tt cell.top.radius}: Same as {\tt yplot[2]}.
  \item {\tt track.margin}: Margins of the cell.
  \item {\tt cell.padding}: Paddings of the cell.
\end{itemize}

One common use of {\tt get.cell.meta.data} is to put inside {\tt panel.fun} when calling
{\tt circos.trackPlotRegion}, then you can get detailed information for the `current` cell
where you want to put graphics.


The core function {\tt circlize} transform from data coordinate (coordinate in the cells) 
to the polar coordinate and {\tt reverse.circlize} transform from polar coordinate to data 
coordinate of a certain cell. The default transformation is applied in the `current` cell.

<<echo = 2:8>>=
pdf(NULL)
factors = c("a", "b")
circos.initialize(factors, xlim = c(0, 1))
circos.trackPlotRegion(ylim = c(0, 1))
circlize(0.5, 0.5, sector.index = "a", track.index = 1)
reverse.circlize(90, 0.9, sector.index = "a", track.index = 1)
reverse.circlize(90, 0.9, sector.index = "b", track.index = 1)
circos.clear()
invisible(dev.off())
@

The results are different for two {\tt reverse.circlize} calls because the reference cells
are different.

{\tt draw.sector} draws sectors, rings or their parts. This is useful if you want to highlight 
some part of your circos plot. As you can guess, this function needs arguments of the position 
of circle center, the start degree and the end degree for sectors, and radius for two edges 
(or one edge) which are up or bottom border of a cell. Actually, {\tt draw.sector} is
independent from the circos plot.

<<eval = FALSE>>=
draw.sector(start.degree, end.degree, rou1)
draw.sector(start.degree, end.degree, rou1, rou2, center)
draw.sector(start.degree, end.degree, rou1, rou2, center, col, border, lwd, lty)
@

Directions from {\tt start.degree} and {\tt end.degree} is important to draw sectors. 
By default, it is clock wise.

<<eval = FALSE>>=
draw.sector(start.degree, end.degree, clock.wise = FALSE)
@

Following code shows some examples of {\tt draw.sector} (figure \ref{fig:circlize_draw_sector_general}).

<<circlize_draw_sector_general, out.width = "0.8\\textwidth", fig.cap = "Examples of {\\tt draw.sector}.">>=
par(mar = c(1, 1, 1, 1))
plot(c(-1, 1), c(-1, 1), type = "n", axes = FALSE, ann = FALSE)
draw.sector(20, 0)
draw.sector(30, 60, rou1 = 0.8, rou2 = 0.5, clock.wise = FALSE, col = "#FF000080")
draw.sector(350, 1000, col = "#00FF0080", border = NA)
draw.sector(0, 180, rou1 = 0.25, center = c(-0.5, 0.5), border = 2, lwd = 2, lty = 2)
draw.sector(0, 360, rou1 = 0.7, rou2 = 0.6, col = "#0000FF80")
@

In order to highlight cells in the circos plot, we can use {\tt get.cell.meta.data} to
get the information of positions of cells. E.g. the start degree
and end degree can be obtained through {\tt cell.start.degree} and {\tt cell.end.degree}, 
and the position of the top border and bottom border on the circle radius can be obtained 
through {\tt cell.top.radius} and {\tt cell.bottom.radius}.  Following code shows several
examples to highlight sectors and tracks (figure \ref{fig:circlize_highlight} A).

<<circlize_highlight_1, eval = FALSE>>=
par(mar = c(1, 1, 1, 1))
factors = letters[1:8]
circos.initialize(factors, xlim = c(0, 1))
for(i in 1:3) {
    circos.trackPlotRegion(ylim = c(0, 1))
}
circos.info(plot = TRUE)
@

If we want to highlight sector a:

<<circlize_highlight_2, eval = FALSE>>=
draw.sector(get.cell.meta.data("cell.start.degree", sector.index = "a"),
            get.cell.meta.data("cell.end.degree", sector.index = "a"),
            rou1 = 1, col = "#FF000040")
@

If we want to highlight track 1:

<<circlize_highlight_3, eval = FALSE>>=
draw.sector(0, 360, 
    rou1 = get.cell.meta.data("cell.top.radius", track.index = 1),
    rou2 = get.cell.meta.data("cell.bottom.radius", track.index = 1),
    col = "#00FF0040")           
@

If we want to highlight track 2 and 3 in sector e and f:

<<circlize_highlight_4, eval = FALSE>>=
draw.sector(get.cell.meta.data("cell.start.degree", sector.index = "e"),
            get.cell.meta.data("cell.end.degree", sector.index = "f"),
            get.cell.meta.data("cell.top.radius", track.index = 2),
            get.cell.meta.data("cell.bottom.radius", track.index = 3),
            col = "#0000FF40")
@

If we want to highlight specific regions such as a small region inside cell ({\tt h:2}),
we can use {\tt circlize} to calculate the exact positions on the circle. But always
keep in mind that x-axis in the cell are always clock wise.

<<circlize_highlight_5, eval = FALSE>>=
pos = circlize(c(0.2, 0.8), c(0.2, 0.8), sector.index = "h", track.index = 2)
draw.sector(pos[1, "theta"], pos[2, "theta"], pos[1, "rou"], pos[2, "rou"], 
    clock.wise = TRUE, col = "#00FFFF40")
circos.clear()
@

If the purpose is simply highlight complete cells, there is a shortcut function
{\tt highlight.sector} for which you only need to specify index for sectors
and tracks that you want to to highlight (figure \ref{fig:circlize_highlight} B).

<<circlize_highlight_sector, eval = FALSE>>=
factors = letters[1:8]
circos.initialize(factors, xlim = c(0, 1))
for(i in 1:4) {
    circos.trackPlotRegion(ylim = c(0, 1))
}
circos.info(plot = TRUE)

highlight.sector(c("a", "h"), track.index = 1)
highlight.sector("c", col = "#00FF0040")
highlight.sector("d", col = NA, border = "red", lwd = 2)
highlight.sector("e", col = "#0000FF40", track.index = c(2, 3))
highlight.sector(c("f", "g"), col = NA, border = "green", 
    lwd = 2, track.index = c(2, 3))
highlight.sector(factors, col = "#FFFF0040", track.index = 4)
circos.clear()
@

<<circlize_highlight, echo = FALSE, out.width = "0.6\\textwidth", out.height = "1.2\\textwidth", fig.width = 6, fig.height = 12, fig.cap = "Highlight sectors and tracks. A) highlight by {\\tt code draw.sector}; B) highlight by {\\tt highlight.sector}.">>=
par(mfrow = c(2, 1))
<<circlize_highlight_1>>
<<circlize_highlight_2>>
<<circlize_highlight_3>>
<<circlize_highlight_4>>
<<circlize_highlight_5>>
text(-0.9, 0.9, "A", cex = 1.5)
<<circlize_highlight_sector>>
text(-0.9, 0.9, "B", cex = 1.5)
par(mfrow = c(1, 1))
@


\subsection{Get information of circos plot}
You can get basic information of your current circos plot by {\tt circos.info}.
The function can be applied at any time.

<<echo = 2:7>>=
pdf(NULL)
factors = letters[1:3]
circos.initialize(factors = factors, xlim = c(1, 2))
circos.info()
circos.trackPlotRegion(ylim = c(0, 1))
circos.info(sector.index = "a", track.index = 1)
circos.clear()
invisible(dev.off())
@

It can also add labels to cells by {\tt circos.info(plot = TRUE)}.

\subsection{Do not forget {\tt circos.clear}}
You should always call {\tt circos.clear} to complete the circos plot. Because there are several
parameters for circos plot which can only be set before {\tt circos.initialize}. So before you draw the next
circos plot, you need to reset all these parameters.

\subsection{A simple example of implementing high-level graphics}

We will show a simple example (figure \ref{fig:circlize_combine}) which combines several 
low-level graphic functions to construct complicated graphics for specific purpose.

In the following code, we make histogram in another circular way. The bars are added by
{\tt circos.rect}, reference lines are added by {\tt circos.lines}, labels are added by
{\tt circos.text} and axes are added by {\tt circos.axis}.

<<circlize_combine, out.width = "0.8\\textwidth", fig.cap = "Combine low-level graphic functions to generate high-level graphics.">>=
category = paste0("category", "_", 1:10)
percent = sort(sample(40:80, 10))
color = rev(rainbow(length(percent)))

par(mar = c(1, 1, 1, 1))
circos.par("start.degree" = 90)
circos.initialize("a", xlim = c(0, 100)) # 'a` just means there is one sector
circos.trackPlotRegion(ylim = c(0.5, length(percent)+0.5), , track.height = 0.8, 
    bg.border = NA, panel.fun = function(x, y) {
        xlim = get.cell.meta.data("xlim") # in fact, it is c(0, 100)
        for(i in seq_along(percent)) {
            circos.lines(xlim, c(i, i), col = "#CCCCCC")
            circos.rect(0, i - 0.45, percent[i], i + 0.45, col = color[i], 
                border = "white")
        }

        for(i in seq_along(percent)) {
            circos.text(xlim[1], i, paste0(category[i], " - ", percent[i], "%"), 
                adj = c(1.1, 0.5)) 
        }

        breaks = seq(0, 90, by = 5)
        circos.axis(h = "top", major.at = breaks, labels = paste0(breaks, "%"),
            major.tick.percentage = 0.02, labels.cex = 0.6, 
                labels.away.percentage = 0.01)
})
circos.clear()
@

\section{Advanced technique}

\subsection{Zooming of sectors}

Under the default settings, width of sectors are calculated according to the range of data 
in each category. In some circumstance, you may want to manually set the width of each 
sector. Normally it is not a good idea since width of sectors can reflect useful information of your data. However, 
sometimes it is useful to modify the width of sectors, e.g., you want to put your plot only 
in half of the circle while in the other half of the circle, zooming of certain sectors are applied.
The width of sectors can be manually set by {\tt sector.width} argument in {\tt circos.initialize}. 
The value for the argument should be a vector with length of either one or as same as the 
number of categories (again, order of {\tt sector.width} vector corresponds to the order of levels of {\tt factors}). 
{\tt sector.width} is relative value, and it will be scaled to percentage 
(e.g. if you set {\tt sector.width} to {\tt c(1, 3)}, it will be scaled as {\tt c(0.25, 0.75)}).

In order to zoom e.g. one sector, the copy of the data corresponding to this sector
should be attached to the original data. Since these two sectors (original sector and 
the zoomed sector) contain the same data, if same plotting functions are applied to them,
there will be same graphics generated.

In the following code, sector a and b are zoomed. To make thing simple, we put all data into 
one data frame. 

<<>>=
df = data.frame(factors = sample(letters[1:6], 100, replace = TRUE),
                x = rnorm(100),
                y = rnorm(100),
                stringsAsFactors = FALSE)
@

Extract the data for sector a and b, and assign to a new variable.

<<>>=
zoom_df = df[df$factors %in% c("a", "b"), ]
@

Modify the names for the zoomed sector, because in the circos plot, zoomed sectors are same
as other normal sectors. Attach to the original data frame.

<<>>=
zoom_df$factors = paste0("zoom_", zoom_df$factors)
df2 = rbind(df, zoom_df)
@

In order to put the normal sectors in half of the circle and the zoomed sectors in the other half,
just normalize the width of normal sectors and normalize the width
of zoomed sectors separately.

<<>>=
xrange = tapply(df2$x, df2$factors, function(x) max(x) - min(x))
normal_sector_index = unique(df$factors)
zoomed_sector_index = unique(zoom_df$factors)
sector.width = c(xrange[normal_sector_index] / sum(xrange[normal_sector_index]), 
                 xrange[zoomed_sector_index] / sum(xrange[zoomed_sector_index]))
@

Now make the circos plot in the normal way.

<<circlize_zoom_1, eval = FALSE>>=
par(mar = c(1, 1, 1, 1))
circos.par(start.degree = 90)
circos.initialize(df2$factors, x = df2$x, sector.width = sector.width)
circos.trackPlotRegion(df2$factors, x = df2$x, y = df2$y, panel.fun = function(x, y) {
    circos.points(x, y, col = "red", pch = 16, cex = 0.5)
    xlim = get.cell.meta.data("xlim")
    ylim = get.cell.meta.data("ylim")
    sector.index = get.cell.meta.data("sector.index")
    circos.text(mean(xlim), mean(ylim), sector.index, niceFacing = TRUE)
})
@

If you want to add links from original sectors to zoomed sectors, 

<<circlize_zoom_2, eval = FALSE>>=
circos.link("a", get.cell.meta.data("cell.xlim", sector.index = "a"),
    "zoom_a", get.cell.meta.data("cell.xlim", sector.index = "zoom_a"),
    border = NA, col = "#00000020")
circos.clear()
@

<<circlize_zoom, echo = FALSE, out.width = "0.8\\textwidth", fig.cap = "Zoom sectors.">>=
<<circlize_zoom_1>>
<<circlize_zoom_2>>
@

\subsection{Draw part of the circos layout}

{\tt canvas.xlim} and {\tt canvas.ylim} in {\tt circos.par} is useful to make figures on only part of circle. In the example,
only sectors between $0^\circ$ to $90^\circ$ are plotted (figure \ref{fig:circlize_part}). First, four sectors
with the same width are initialized. Then only the first sector is drawn with points and lines. From figure \ref{fig:circlize_part},
we in fact created the whole circle, but only a quarter of the circle is in the canvas region. Codes are as follows. 

<<eval = FALSE>>=
par(mar = c(1, 1, 1, 1))
circos.par("canvas.xlim" = c(0, 1), "canvas.ylim" = c(0, 1),
    "clock.wise" = FALSE, "gap.degree" = 0)
factors = letters[1:4]
circos.initialize(factors = factors, xlim = c(0, 1))
circos.trackPlotRegion(factors = factors, ylim = c(0, 1), bg.border = NA)
circos.updatePlotRegion(sector.index = "a", bg.border = "black")
x1 = runif(100)
y1 = runif(100)
circos.points(x1, y1, pch = 16, cex = 0.5)
circos.trackPlotRegion(factors = factors, ylim = c(0, 1), bg.border = NA)
circos.updatePlotRegion(sector.index = "a", bg.border = "black")
circos.lines(1:100/100, y1, pch = 16, cex = 0.5)
circos.clear()
@


<<circlize_part, echo = FALSE, out.width = "0.6\\textwidth", out.height = "1.2\\textwidth", fig.width = 6, fig.height = 12, fig.cap = "One quarter of the circle.">>=
source("src/intro-17-part.R")
@

In the second situation, in some tracks, you only need to add graphic on subset of sectors.
Remember when you are creating new track with {\tt circos.trackPlotRegion} and set {\tt bg.col} and {\tt bg.border}
to {\tt NA}, it means create the new track while draw nothing. After that, you can use {\tt circos.updatePlotRegion} to update
these invisible cells of interest and add graphics on it (figure \ref{fig:circlize_part2}).

<<eval=FALSE>>=
par(mar = c(1, 1, 1, 1))
factors = letters[1:4]
circos.initialize(factors = factors, xlim = c(0, 1))
circos.trackPlotRegion(factors = factors, ylim = c(0, 1), bg.col = NA, bg.border = NA)
circos.updatePlotRegion(sector.index = "a", bg.border = "black")
x1 = runif(100)
y1 = runif(100)
circos.points(x1, y1, pch = 16, cex = 0.5)

circos.trackPlotRegion(factors = factors, ylim = c(0, 1),bg.col = NA, bg.border = NA)
circos.updatePlotRegion(sector.index = "a", bg.border = "black")
x1 = runif(100)
y1 = runif(100)
circos.points(x1, y1, pch = 16, cex = 0.5)

circos.trackPlotRegion(factors = factors, ylim = c(0, 1))
circos.trackPlotRegion(factors = factors, ylim = c(0, 1))
circos.clear()
@

<<circlize_part2, echo = FALSE, out.width = "0.8\\textwidth", fig.cap = "Only plot subset of sectors in certain tracks.">>=
source("src/intro-18-part2.R")
@



\subsection{Combine more than one circos plots}

Since circular layout by \textbf{circlize} is finally plotted in an ordinary R plotting system.
Two seperated circular layouts can be plotted together by some tricks. Here the key is 
{\tt par(new = TRUE)} which allows to draw a new figure on the previous canvas region.
{\bf Just remember the radius of the circos is always 1.}

The first example is to make one outer circos plot and an inner circos plot (figure \ref{fig:circlize_nested}).

<<eval=FALSE>>=
par(mar = c(1, 1, 1, 1))
factors = letters[1:4]
circos.initialize(factors = factors, xlim = c(0, 1))
circos.trackPlotRegion(ylim = c(0, 1), panel.fun = function(x, y) {
    circos.text(0.5, 0.5, "outer circos")
})
circos.clear()

par(new = TRUE)
circos.par("canvas.xlim" = c(-2, 2), "canvas.ylim" = c(-2, 2))
factors = letters[1:3]
circos.initialize(factors = factors, xlim = c(0, 1))
circos.trackPlotRegion(ylim = c(0, 1), panel.fun = function(x, y) {
    circos.text(0.5, 0.5, "inner circos")
})
circos.clear()
@

<<circlize_nested, echo = FALSE, out.width = "\\textwidth", fig.cap = "An outer circos plot plus an inner one.">>=
source("src/intro-19-nested.R")
@

The second example is to make two separated circos plot in which every
circos plot only contains a half (figure \ref{fig:circlize_separated}).

<<eval=FALSE>>=
par(mar = c(1, 1, 1, 1))
factors = letters[1:4]
circos.par("canvas.xlim" = c(-1, 1.5), "canvas.ylim" = c(-1, 1.5), start.degree = -45)
circos.initialize(factors = factors, xlim = c(0, 1))
circos.trackPlotRegion(ylim = c(0, 1), bg.col = NA, bg.border = NA)
circos.updatePlotRegion(sector.index = "a")
circos.text(0.5, 0.5, "first one")
circos.updatePlotRegion(sector.index = "b")
circos.text(0.5, 0.5, "first one")

circos.clear()

par(new = TRUE)
circos.par("canvas.xlim" = c(-1.5, 1), "canvas.ylim" = c(-1.5, 1), start.degree = -45)
circos.initialize(factors = factors, xlim = c(0, 1))
circos.trackPlotRegion(ylim = c(0, 1), bg.col = NA, bg.border = NA)
circos.updatePlotRegion(sector.index = "d")
circos.text(0.5, 0.5, "second one")
circos.updatePlotRegion(sector.index = "c")
circos.text(0.5, 0.5, "second one")

circos.clear()
@

<<circlize_separated, echo = FALSE, out.width = "\\textwidth", fig.cap = "Two separated circos plots">>=
source("src/intro-20-seperated.R")
@

The third example is to draw sectors with different radius (figure \ref{fig:circlize_diff_radius}). In fact,
it makes four circos plots in which only one sector of each graphs is plotted. Note links
can not be drawn in these different sectors because links can only be drawn in one circos
plot. 

<<eval=FALSE, echo=TRUE>>=
library(circlize)
par(mar = c(1, 1, 1, 1))
factors = letters[1:4]
lim = c(1, 1.1, 1.2, 1.3)
for(i in 1:4) {
    circos.par("canvas.xlim" = c(-lim[i], lim[i]),
        "canvas.ylim" = c(-lim[i], lim[i]), "track.height" = 0.4)
    circos.initialize(factors = factors, xlim = c(0, 1))
    circos.trackPlotRegion(ylim = c(0, 1), bg.border = NA)
    circos.updatePlotRegion(sector.index = factors[i], bg.border = "black")
    circos.points(runif(10), runif(10), pch = 16)
    circos.clear()
    par(new = TRUE)
}
par(new = FALSE)
@

It is different from example in ``Draw part of the circos layout'' section. In that example,
cells both visible and invisible all belong to a same track and they are in a same circos plot, so they
should have same radius. But here, cells have different radius and they
belong to different circos plot.


<<circlize_diff_radius, echo = FALSE, out.width = "0.8\\textwidth", fig.cap = "Sectors with different radius.">>=
source("src/intro-21-diffradius.R")
@


\subsection{Draw outside and combine with canvas coordinate}

Sometimes it is very useful to draw something outside plotting region. (You can think it is
similar as {\tt par(xpd = NA)} setting.) The following is a simple
example to illustrate such circumstance (figure \ref{fig:circlize_outside}).

<<eval=FALSE, echo=TRUE>>=
set.seed(12345)
par(mar = c(1, 1, 1, 1))
factors = letters[1:4]
circos.par("canvas.xlim" = c(-1.5, 1.5), "canvas.ylim" = c(-1.5, 1.5), "gap.degree" = 10)
circos.initialize(factors = factors, xlim = c(0, 1))
circos.trackPlotRegion(ylim = c(0, 1), panel.fun = function(x, y) {
    circos.points(1:20/20, 1:20/20)
})
circos.lines(c(1/20, 0.5), c(1/20, 3), sector.index = "d", straight = TRUE)
circos.text(0.5, 3, "mark", sector.index = "d", adj = c(0.5, 0))

circos.trackPlotRegion(ylim = c(0, 1), panel.fun = function(x, y) {
    circos.points(1:20/20, 1:20/20)
})
text(0, 0, "this is\nthe center", cex = 1.5)
legend("bottomleft", pch = 1, legend = "this is the legend")
circos.clear()
@

Since the final graphics are plotted in an ordinary canvas plotting region, we can add additional graphics through
the traditional way, such as legends, texts, ...

<<circlize_outside, echo = FALSE, out.width = "0.8\\textwidth", fig.cap = "Draw outside the cell and combine with canvas coordinate.">>=
source("src/intro-22-outside.R")
@


\subsection{Arrange figures with layouts}

You can use {\tt layout} to arrange multiple figures together (also it is available by {\tt par(mfrow)}
or {\tt par(mfcol)}) (figure \ref{fig:circlize_layout}). 

<<circlize_layout, out.width = "\\textwidth", fig.cap = "Arrange multiple circos plots.">>=
layout(matrix(1:9, 3, 3))
for(i in 1:9) {
    factors = 1:8
    par(mar = c(0.5, 0.5, 0.5, 0.5))
    circos.par(cell.padding = c(0, 0, 0, 0))
    circos.initialize(factors, xlim = c(0, 1))
    circos.trackPlotRegion(ylim = c(0, 1), track.height = 0.05,
        bg.col = rand_color(8), bg.border = NA)
    for(i in 1:20) {
        se = sample(1:8, 2)
        circos.link(se[1], runif(2), se[2], runif(2), 
            col = rand_color(1, transparency = 0.4))
    }
    circos.clear()
}
@


\end{document}
