ggchord: sequence plots and composition

ggchord

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

Install from GitHub

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

install.packages("remotes")
remotes::install_github("DangJem/ggchord", dependencies = NA)

Environment and installation checks

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.

getRversion()
packageVersion("ggplot2")
packageVersion("ggchord")
find.package("ggchord")

Load and draw

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.

Optional packages and input files

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.

If installation fails

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.

Related sections

Plotting concepts · Input tables · Save a figure

Shared data and layers

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

Run this section in a fresh R session after following the installation instructions.

library(ggchord)
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")
Default arc backbones for four sequences
Default arc backbones for four sequences

Read the plot

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

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

Add a CDS

Select the original annotation starting at 43,765 bp on OQ646790.1 and recover its biological strand.

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")
One integrase CDS added to the green backbone
One integrase CDS added to the green backbone

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

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")
Add the feature name while retaining backbones, ribbon and CDS
Add the feature name while retaining backbones, ribbon and CDS

Switch to a linear layout

p_chord_linear <- p_chord_gene_labels + coord_collinear()
view_ggchord(p_chord_linear, width = 8, height = 5, units = "in")
Collinear
Collinear

This retains the ribbon, CDS and feature-name layers; Collinear selects adjacent rows by default. Compare all four views in the next section.

Use your own sequences

Replace seq_data_example with a table containing accver and length. See Basic input tables for the column definitions, Flexible parameter formats for local settings, and Four-view comparison for a strict coordinate comparison.

Circular backbone and annotations

Length and a prepared annotation

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.

library(ggchord)
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
Circular backbone

Add the feature and its label

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
Circular feature and label

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

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

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

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.

library(ggchord)
library(dplyr)

Plot original HSP endpoints

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. Preparation requires optional dplyr.

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.

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")
All 11 source-backed EMALE PAF HSPs in one-based native coordinates; reverse alignments retain their negative slope.
All 11 source-backed EMALE PAF HSPs in one-based native coordinates; reverse alignments retain their negative slope.

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.

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

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.

Data preparation and settings (expand)
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)
  )
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)
  )
Four-sequence HSP matrix
Four-sequence HSP matrix · Complete R source

Inspect source 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:

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

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.

map_ggchord_position(
  flag_dotplot, flagship_hsp$qaccver[1], flagship_hsp$qstart[1], axis = "x"
)

Boundaries and next steps

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. Example: trace four endpoints of one segment and explain slope and colour separately.

Panels and source-interval connections

Start with two independent plots

Use ggchord, dplyr and bundled sequence_detail_example$paf; original provenance is available in the input bundle. Print course_center and course_detail separately before composing one observed relationship.

library(ggchord)
library(dplyr)
Data preparation and settings (expand)
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)
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
Independent center plot
Independent detail plot
Independent detail plot
Two panels and one source relationship
Two panels and one source relationship

Check intervals, panels and instances

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.

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

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

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.

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()