---
title: "ggchord: sequence plots and composition"
output:
  rmarkdown::html_vignette:
    self_contained: true
    css: vignette.css
vignette: >
  %\VignetteIndexEntry{ggchord: sequence plots and composition}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

<!-- Generated by tools/sync-tutorials.py; edit website/ and tools/documentation-examples.R. -->

```{r setup, include=FALSE}
knitr::opts_chunk$set(eval = FALSE, collapse = TRUE, comment = "#>")
```

<img src="tutorial-assets/logo.png" alt="ggchord" width="200">

Choose among four plotting modules. Each opening example includes its own setup. Continue online for data import, advanced workflows and complete research examples.


## Download and installation {#installation}

### Install from GitHub {#installation-requirements}

Install ggchord and its required dependencies from the project repository. Source installation requires a working R development environment.

```{r example-1, eval=FALSE}
install.packages("remotes")
remotes::install_github("DangJem/ggchord", dependencies = NA)
```

### Environment and installation checks {#installation-environment}

Requires R ≥ 4.1.0 and ggplot2 ≥ 4.0.0. Inspect the packages actually used by the current session and include this output when reporting a problem.

```{r example-2, eval=FALSE}
getRversion()
packageVersion("ggplot2")
packageVersion("ggchord")
find.package("ggchord")
```

### Load and draw {#installation-first-plot}

```{r example-3, eval=FALSE}
library(ggchord)

p <- ggchord(seq_data_example) +
  geom_seq() +
  geom_seq_label() +
  coord_chord()
p
```

Success produces four arcs with different lengths and sequence IDs, without a build error. For missing functions, inspect the library path and loaded package before checking the matching [function reference](https://dangjem.github.io/ggchord/en/reference/index.html).

### Optional packages and input files {#installation-support-evidence}

Examples that use dplyr, Biostrings or a format decoder declare that dependency beside the code. Install it only for the corresponding workflow. Built-in data works offline; file examples use the [input archive](https://dangjem.github.io/ggchord/en/formats.html).

### If installation fails {#installation-troubleshooting}

| Symptom | First check | Action |
| --- | --- | --- |
| Repository or index cannot download | First network error, proxy and GitHub access | Restore access and retry without changing data |
| Missing or outdated dependency | Dependency named in the error and minimum R | Install/update that dependency, then retry |
| Source compilation fails | First compiler error and platform build tools | Install the appropriate R development tools and retain the log |
| Installation succeeds but functions are missing | `find.package()` and the loaded library | Restart R, load the correct library and retry the minimal plot |

For input and plotting problems, see [diagnostics](https://dangjem.github.io/ggchord/en/diagnostics.html).

### Related sections {#installation-first-steps}

[Plotting concepts](https://dangjem.github.io/ggchord/en/modes.html) · [Input tables](https://dangjem.github.io/ggchord/en/data.html) · [Save a figure](https://dangjem.github.io/ggchord/en/output.html)


<span id="input"></span><span id="read"></span><span id="save"></span><span id="source"></span><span id="stable"></span><span id="verified-versions"></span>


## Shared data and layers {#multi-sequence-start}

Build backbones, a link, a feature and labels in one section using bundled source records. Run in order; this section uses ggchord and optional dplyr.

### Draw the backbones {#multi-sequence-start-draw}

Run this section in a fresh R session after following the [installation instructions](#installation).


```{r example-4, eval=FALSE}
library(ggchord)
```



```{r example-5, eval=FALSE}
p_chord_backbone <- ggchord(seq_data = seq_data_example) +
  geom_seq() +
  geom_seq_label() +
  coord_chord()
view_ggchord(p_chord_backbone, width = 7, height = 7, units = "in")
```


<figure class="documentation-figure"><img src="tutorial-assets/frontbackbone.jpg" alt="Default arc backbones for four sequences" width="1008" height="1008" loading="lazy"><figcaption>Default arc backbones for four sequences</figcaption></figure>

### Read the plot {#multi-sequence-start-read}

Each arc represents a row of the sequence table. Find `MT108731.1` by its label and compare it with `MT118296.1`. These two sequences are 64,323 bp and 32,090 bp, so the first arc is about twice as long as the second.

`geom_seq()` draws the backbones, `geom_seq_label()` adds their IDs, and `coord_chord()` arranges the backbones as arcs.

### What the label layer controls {#multi-sequence-start-try}

Remove the `geom_seq_label()` line and run the code again. The arcs stay in place and the sequence names disappear.

### Add an alignment ribbon {#multi-sequence-start-links}

Take the first row of the bundled alignment table. It connects two of the four sequences.


```{r example-6, eval=FALSE}
chord_links <- head(ribbon_data_example, 1)

p_chord_ribbon <- p_chord_backbone +
  geom_link_ribbon(data = chord_links)
view_ggchord(p_chord_ribbon, width = 7, height = 7, units = "in")
```


<figure class="documentation-figure"><img src="tutorial-assets/frontribbon.png" alt="One alignment ribbon added" width="1008" height="1008" loading="lazy"><figcaption>One alignment ribbon added</figcaption></figure>

Follow the ribbon to both ends. It spans 26,298–51,139 bp on `MT108731.1` and 7,121–31,959 bp on `MT118296.1`. Each end covers an interval, so this layer uses `geom_link_ribbon()`.

The default colour reflects the alignment identity for this row, about 98.6%. The crossed shape comes from how the interval ends are joined. Use the alignment coordinates to assess inversion.

### Add a CDS {#multi-sequence-start-add-genes}

<span id="prepare"></span><span id="inspect-genes"></span><span id="genes"></span>Select the original annotation starting at 43,765 bp on `OQ646790.1` and recover its biological strand.


```{r example-7, eval=FALSE}
chord_genes_example <- subset(gene_data_example, accver == "OQ646790.1" & start == 43765)
chord_genes_example$strand <- chord_genes_example$source_strand

p_chord_feature <- p_chord_ribbon +
  geom_gene(data = chord_genes_example)
view_ggchord(p_chord_feature, width = 7, height = 7, units = "in")
```


<figure class="documentation-figure"><img src="tutorial-assets/frontfeature.png" alt="One integrase CDS added to the green backbone" width="1008" height="1008" loading="lazy"><figcaption>One integrase CDS added to the green backbone</figcaption></figure>

Find the red arrow on green `OQ646790.1`. It marks the plus-strand integrase CDS from 43,765 to 46,140 bp. The ribbon and this CDS use independent input tables.

To display the CDS name, add `geom_gene_label(data = chord_genes_example)`. It reads the label from `anno`. 

### Display the feature name {#multi-sequence-start-labels}


```{r example-8, eval=FALSE}
p_chord_gene_labels <- p_chord_feature +
  geom_gene_label(data = chord_genes_example, label_radial_offset = 0.10)
view_ggchord(p_chord_gene_labels, width = 7, height = 7, units = "in")
```


<figure class="documentation-figure"><img src="tutorial-assets/frontgenelabels.png" alt="Add the feature name while retaining backbones, ribbon and CDS" width="1008" height="1008" loading="lazy"><figcaption>Add the feature name while retaining backbones, ribbon and CDS</figcaption></figure>

### Switch to a linear layout {#multi-sequence-start-collinear}


```{r example-9, eval=FALSE}
p_chord_linear <- p_chord_gene_labels + coord_collinear()
view_ggchord(p_chord_linear, width = 8, height = 5, units = "in")
```


![Collinear](../man/figures/frontlabelledlinear.png)

This retains the ribbon, CDS and feature-name layers; Collinear selects adjacent rows by default. Compare all four views in the [next section](https://dangjem.github.io/ggchord/en/multi-sequence-views.html).

### Use your own sequences {#multi-sequence-start-adapt}

Replace `seq_data_example` with a table containing `accver` and `length`. See [Basic input tables](https://dangjem.github.io/ggchord/en/data.html#prepare) for the column definitions, [Flexible parameter formats](https://dangjem.github.io/ggchord/en/parameters.html) for local settings, and [Four-view comparison](https://dangjem.github.io/ggchord/en/multi-sequence-views.html#input) for a strict coordinate comparison.


## Circular backbone and annotations {#circular-start}

### Length and a prepared annotation {#circular-start-input}

Only lengths and prepared tables are needed. The ori row is the verified pUC19 annotation 867–1455, matching the original inspectorigin output; no DNA recognition is run. Dependencies: ggchord and dplyr.

```{r example-10, eval=FALSE}
library(ggchord)
```


```{r example-11, eval=FALSE}
library(dplyr)
circle_seqs <- plasmid_example_pUC19 |> select(accver, length)
circle_origins <- tibble(
  accver = "pUC19", start = 867, end = 1455,
  strand = "-", type = "rep_origin", anno = "ori"
)
p_coursecircle <- ggchord(circle_seqs) +
  geom_seq() + geom_seq_center_label() + coord_circular()
```


![Circular backbone](../man/figures/coursecircle.png)

### Add the feature and its label {#circular-start-features-and-labels}


```{r example-12, eval=FALSE}
p_coursecirclefeature <- p_coursecircle +
  geom_feature_plasmid(data = circle_origins) +
  geom_feature_label(data = circle_origins,
    label_side = "inside", label_radial_offset = 0.12, size = 4)
view_ggchord(p_coursecirclefeature, width = 10, height = 8, units = "in")
```


![Circular feature and label](../man/figures/coursecirclefeature.png)

Locate both ori endpoints on the ticks and trace the label to anno. A circular display is not evidence of molecular topology.

### Preview and save {#circular-start-exercise}

Remove the label layer and rerun; backbone and source interval stay unchanged. Replace the row with your own known annotation.

```{r example-13, eval=FALSE}
circular_width <- 10
circular_height <- 8
view_ggchord(p_coursecirclefeature,
  width = circular_width, height = circular_height, units = "in")
ggsave("circular-first.png", p_coursecirclefeature,
  width = circular_width, height = circular_height, units = "in", dpi = 144)
```


## HSP axes, orientation and mapping {#dotplot-start}

See `help("flagship_examples", package = "ggchord")` for provenance, display selections and rebuilding. This page loads bundled inputs directly and focuses on plotting settings.

Start with observed HSPs from one sequence pair, then extend to a four-sequence matrix. The minimal inputs are complete sequence lengths and four HSP endpoints; annotations are optional.


```{r example-14, eval=FALSE}
library(ggchord)
library(dplyr)
```


### Plot original HSP endpoints {#dotplot-start-dotplot}

Bundled `sequence_detail_example$paf` retains the 11 observed HSPs for the EMALE pair; sequence lengths declared by the source file define both axes.
The table is already normalized to one-based coordinates; reverse-alignment target endpoints remain descending.
Original files and provenance are available under [input downloads](https://dangjem.github.io/ggchord/en/formats.html). Preparation requires optional `dplyr`.


```{r example-15, eval=FALSE}
library(dplyr)
dotplot_hsp <- sequence_detail_example$paf
dotplot_seqs <- bind_rows(
  dotplot_hsp |> transmute(accver = qaccver, length = qlen),
  dotplot_hsp |> transmute(accver = saccver, length = slen)
) |>
  distinct()
```


Each line runs from `(qstart, sstart)` to `(qend, send)`. `geom_seq()` is not
required. Use `link_*` mappings and scales for colour, alpha, width and type.
The default Identity domain is 0–100 with ticks 0/50/80/90/95/100; an explicit
user scale overrides it.


```{r example-16, eval=FALSE}
p_viewdotplot <- ggchord(dotplot_seqs, dotplot_hsp) +
  geom_alignment_segment(aes(link_colour = pident), linewidth = 0.65) +
  coord_dotplot()
view_ggchord(p_viewdotplot, width = 8, height = 7, units = "in")
```


<figure class="documentation-figure"><img src="tutorial-assets/viewdotplot.png" alt="All 11 source-backed EMALE PAF HSPs in one-based native coordinates; reverse alignments retain their negative slope." width="1152" height="1008" loading="lazy"><figcaption>All 11 source-backed EMALE PAF HSPs in one-based native coordinates; reverse alignments retain their negative slope.</figcaption></figure>

The legacy constructor may warn about descending endpoints in these valid reverse HSPs. Keep the normalized ordering; sorting each interval would erase the displayed inversion.

`x_seqs` and `y_seqs` independently select/order accessions. `gap` is display
spacing in native bp/aa, not omitted source sequence. Axis directions accept
1/-1 or complete named vectors. Display reversal changes the slope without
changing the biological source table. Each axis starts at source position 1;
concatenated segments retain their own accession and local tick labels.


```{r example-17, eval=FALSE}
dotplot_reversed <- ggchord(dotplot_seqs, dotplot_hsp) +
  geom_alignment_segment(aes(link_colour = pident), linewidth = 0.65) +
  coord_dotplot(y_orientation = -1)
dotplot_layout <- export_ggchord_layout(dotplot_reversed)
dotplot_layout$axis_layout
```


Use `map_ggchord_position(..., axis = "x"/"y")` for native/global conversion,
with `inverse = TRUE` to go back. Display gaps return NA. Focused source
origins use `source = TRUE`; default axis labels stay window-relative.
Unknown directions are warned, omitted and reported; contradictory direction
metadata is rejected. Repeated declared HSP IDs require `allow_repeated=TRUE`
in all participating layers. Unidentified duplicate/self rows remain distinct.
Without cg/cs/CIGAR or another alignment trace, these are HSP segments, not
base-level mismatches or gap paths.

### Multi-sequence HSP matrix {#dotplot-start-matrix}

The following code directly uses bundled `flagship_dotplot_example`, with counts and label tables already prepared. It retains all 32 HSPs across four sequences without inventing self-alignments, symmetric records or missing HSPs. The 266 CDS belong to the shared source table but are not passed to the Dotplot segment layer. Empty regions indicate no relationship records in this input, not an absence of homology.

Column headers identify each query sequence and its complete 1–length range; row headers identify subject sequences and ranges. Bottom and right ticks show local positions within each sequence. Follow a column and row to locate a pair. Each outlined rectangle retains widths and heights proportional to the actual lengths. Pale backgrounds distinguish cells and do not encode similarity; spaces between rectangles are display gaps.

Each of the six unordered sequence pairs supplies only one query→subject direction, with no swapped records or self-alignments. HSPs therefore occupy one half of the matrix. Cells identify record counts or missing input. This is not a rendering omission, and an empty counterpart does not establish absent homology. The plot does not mirror records, add a diagonal or run new alignments. This preparation also uses optional tidyr.


<details class="preparation"><summary>Data preparation and settings (expand)</summary>


```{r example-18, eval=FALSE}
library(ggchord)
library(dplyr)
flagship_paper <- "#FFFCF5"
flagship_sequences <- flagship_dotplot_example$seq_data
flagship_hsp <- flagship_dotplot_example$links
flagship_theme <- theme_ggchord_publication() +
  theme(
    plot.background = element_rect(fill = flagship_paper, colour = NA),
    panel.background = element_rect(fill = flagship_paper, colour = NA),
    legend.background = element_rect(fill = flagship_paper, colour = NA),
    legend.key = element_rect(fill = flagship_paper, colour = NA),
    legend.position = "right", legend.box = "vertical", legend.text = element_text(size = 8),
    legend.title = element_text(size = 9),
    plot.margin = margin(12, 16, 12, 16)
  )
```

</details>



```{r example-19, eval=FALSE}
dotplot_pair_counts <- flagship_dotplot_example$pair_counts
dotplot_cells <- flagship_dotplot_example$cell_labels
flag_dotplot <- ggchord(flagship_sequences, flagship_hsp) +
  geom_alignment_segment(aes(link_colour = pident, link_linewidth = length), alpha = 0.85) +
  scale_link_linewidth_continuous(range = c(0.8, 1.8), name = "HSP length (bp)") +
  coord_dotplot(x_seqs = flagship_sequences$accver, y_seqs = flagship_sequences$accver,
    gap = 4000) +
  ggplot2::geom_text(data = dotplot_cells, aes(x = x, y = y, label = label),
    inherit.aes = FALSE, hjust = 0, vjust = 1, size = 2.8, colour = "#566E67") +
  labs(title = "Six observed sequence pairs · 32 HSPs",
    subtitle = "One query→subject direction per pair; empty cells contain no input records") +
  flagship_theme +
  theme(
    panel.grid = element_blank(), legend.position = "bottom", legend.box = "horizontal",
    axis.text = element_text(size = 9),
    axis.text.x.top = element_text(size = 10, face = "bold", margin = margin(b = 9)),
    axis.text.y.left = element_text(size = 10, face = "bold", margin = margin(r = 9)),
    axis.text.y.right = element_text(size = 9),
    axis.ticks.length = unit(1.5, "mm"),
    plot.margin = margin(12, 16, 12, 16)
  )
```


<figure class="documentation-figure" data-figure="flagdotplot"><img src="tutorial-assets/flagdotplot.png" alt="Four-sequence HSP matrix" width="1872" height="1728" loading="lazy" decoding="async"><figcaption>Four-sequence HSP matrix · <a href="tutorial-assets/site-flagships.R">Complete R source</a></figcaption></figure>

### Inspect source direction {#dotplot-start-direction}

Relative endpoint direction comes from the source record. Reversing a display axis changes the visible slope while leaving the source direction unchanged. Count the supplied directions per sequence pair:

```{r example-20, eval=FALSE}
hsp_direction <- flagship_hsp |>
  mutate(relative_direction = if_else(
    (qend - qstart) * (send - sstart) < 0, "reverse", "forward"
  )) |>
  count(qaccver, saccver, relative_direction, name = "HSP")
hsp_direction
```

### Query an exact position {#dotplot-start-mapping}

Map the first HSP query start onto the concatenated x `axis`. Inverse lookup uses `inverse = TRUE` and an explicit `axis`; display gaps return NA. The four endpoints remain unchanged.

```{r example-21, eval=FALSE}
map_ggchord_position(
  flag_dotplot, flagship_hsp$qaccver[1], flagship_hsp$qstart[1], axis = "x"
)
```

### Boundaries and next steps {#dotplot-start-support}

Backbone gene/feature/track/ribbon layers, facets and Fusion endpoints are unsupported. To inspect gaps or mismatches, provide actual aligned characters; see [the alignment workflow](https://dangjem.github.io/ggchord/en/aligned-sequences.html). Example: trace four endpoints of one segment and explain slope and colour separately.


## Panels and source-interval connections {#fusion-start}

### Start with two independent plots {#fusion-start-panels}

Use ggchord, dplyr and bundled `sequence_detail_example$paf`; original provenance is available in the [input bundle](https://dangjem.github.io/ggchord/assets/tutorial-inputs.zip). Print course_center and course_detail separately before composing one observed relationship.

```{r example-22, eval=FALSE}
library(ggchord)
library(dplyr)
```


<details class="preparation"><summary>Data preparation and settings (expand)</summary>


```{r example-23, eval=FALSE}
library(dplyr)
fusion_hsp <- sequence_detail_example$paf
fusion_seqs <- bind_rows(
  fusion_hsp |> transmute(accver = qaccver, length = qlen),
  fusion_hsp |> transmute(accver = saccver, length = slen)
) |>
  distinct()
fusion_colours <- setNames(c("#0072B2", "#D55E00"), fusion_seqs$accver)
fusion_links <- fusion_hsp |>
  filter(length >= 900, pident >= 85)
fusion_events <- fusion_hsp |>
  transmute(accver = qaccver, pos = qstart)
```

</details>



```{r example-24, eval=FALSE}
course_center <- ggchord(fusion_seqs |> slice(1)) +
  geom_seq(show.legend = FALSE) +
  coord_circular()
course_detail <- ggchord(fusion_seqs) +
  geom_seq(show.legend = FALSE) +
  geom_seq_label() +
  coord_collinear(seq_axis = "vertical")
p_coursefusion <- ggchord_fusion(course_center) +
  fusion_panel(course_detail, id = "detail", side = "right") +
  fusion_ribbon(
    fusion_links |> slice(1), qpanel = "center", spanel = "detail",
    fill = "#269B82", alpha = 0.35
  )
view_ggchord(p_coursefusion, width = 12, height = 8, units = "in")
```


![Independent center plot](../man/figures/coursefusioncenter.png)

![Independent detail plot](../man/figures/coursefusiondetail.png)

![Two panels and one source relationship](../man/figures/coursefusion.png)

### Check intervals, panels and instances {#fusion-start-intervals}

Fusion is a composition, not a seventh Coord. Each panel retains its data, layers, scales and physical ratio. A side places a panel without rotating it. Endpoints must share units, be fully visible and route unambiguously; direct bp–aa links are unsupported.

```{r example-25, eval=FALSE}
fusion_width <- 12
fusion_height <- 8
view_ggchord(p_coursefusion,
  width = fusion_width, height = fusion_height, units = "in")
course_export <- export_ggchord_fusion(p_coursefusion,
  width = fusion_width, height = fusion_height)
course_export$connections
course_export$fronts
```

### Save at the same size {#fusion-start-save}

```{r example-26, eval=FALSE}
ggsave("fusion-first.png", p_coursefusion,
  width = fusion_width, height = fusion_height, units = "in", dpi = 144)
```

Example: choose another real HSP and identify qpanel/spanel and its source row. Dotplot, facets and unregistered external plots are unsupported.


## HSP Dotplot and radial spokes {#view-expansion}

Use the existing source tables; no extra alignment table is required. Dotplot segments retain all four HSP endpoints. Radial spokes use cyclic existing relationships and proportional lengths. See the website view-expansion chapter for source preparation, supported layers and inverse mapping.

```{r example-27, eval=FALSE}
ggchord(seq_data_example, ribbon_data_example) +
  geom_alignment_segment(aes(link_colour = pident)) +
  coord_dotplot()

ggchord(seq_data_example, ribbon_data_example) +
  geom_seq() +
  geom_link_ribbon() +
  geom_seq_label() +
  coord_radial_synteny()
```
