| Title: | Layered Chord, Circular and Linear Sequence Visualization |
| Version: | 0.28.2 |
| Description: | A 'ggplot2'-based package for multi-sequence alignment chord diagrams, linear and radial synteny plots, high-scoring segment pair dot plots and single circular sequence maps and static cross-panel interval compositions. A layered grammar combines sequence backbones, interval links, genes, general biological features, labels, quantitative tracks, genomic axes and restriction sites. Feature placement is expressed with reusable Position objects, while role-specific scales and themes keep data mapping separate from geometry and appearance. |
| License: | MIT + file LICENSE |
| Depends: | R (≥ 4.1.0) |
| Imports: | ggplot2 (≥ 4.0.0), grDevices, grid, rlang, scales, utils |
| VignetteBuilder: | knitr |
| Suggests: | knitr, rmarkdown, qpdf, dplyr, purrr, tidyr, svglite, testthat (≥ 3.0.0), readxl, digest, GenomicRanges, InteractionSet, IRanges, S4Vectors, jsonlite, Biostrings, colorspace, rtracklayer, VariantAnnotation, StructuralVariantAnnotation, GenomicAlignments, Rsamtools |
| Encoding: | UTF-8 |
| LazyData: | true |
| URL: | https://github.com/DangJem/ggchord, https://dangjem.github.io/ggchord/ |
| BugReports: | https://github.com/DangJem/ggchord/issues |
| NeedsCompilation: | no |
| Config/roxygen2/version: | 8.0.0 |
| Config/Needs/website: | pkgdown, jsonlite, pkgload |
| Packaged: | 2026-11-15 15:04:47 UTC; root |
| Author: | Jem Dang [aut, cre] |
| Maintainer: | Jem Dang <dangjem0730@gmail.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-11-16 08:50:17 UTC |
Combine a ggchord plot with ggplot2 objects
Description
Uses ggplot2's standard composition semantics for layers, scales, themes, coordinates and annotations.
Usage
## S3 method for class 'ggchord'
e1 + e2
Arguments
e1 |
A ggchord object |
e2 |
A ggplot2 component. |
Value
A ggchord object
Choose target-size styles and joint guide layout
Description
Add this policy to a ggchord plot. The ordinary print, ggsave, preview and diagnostic paths rebuild at the actual device or Fusion panel size. Plots without a policy retain their existing behaviour.
Usage
adapt_ggchord(
mode = c("adaptive", "fixed", "scale"),
reference_size = c(8, 6),
text_scale_range = c(0.85, 1.35),
min_text_size = 2.5
)
Arguments
mode |
One of |
reference_size |
Positive width and height in inches. Scale modes use the fourth root of target/reference area, with a bounded text multiplier. |
text_scale_range |
Lower and upper positive text multipliers containing
|
min_text_size |
Lower bound in mm for automatically reduced theme text. Defaults already smaller than this value are preserved rather than enlarged. Explicit text sizes and existing label-fit policies keep their own contracts. |
Details
fixed keeps default theme sizes and guide furniture at their reference
physical sizes. scale adjusts theme-driven default text, lines and spacing
within bounds. adaptive additionally selects a joint arrangement of trained
native legends and colour bars, then remeasures the complete plot. Existing
label layout is rerun with the resulting sizes; this is not a new global
label collision solver. Data, source coordinates and scale mappings are unchanged.
Omitted fixed line widths in native backbone, link, ribbon and alignment
layers follow the bounded line factor. Explicit widths and mapped widths
retain their own values and scale rules. Other geometry constants and native
theme-derived aesthetic expressions are not uniformly multiplied.
Explicit geom styles, mapped sizes, theme fields and guide constraints take priority. Only unspecified guide grids, directions and positions can change. Continuous/stepped bars stay intact and retain their scale breaks and order. Unknown custom guides are measured but not rearranged. Infeasible layouts warn and report their constraints; categories are never silently removed.
Apply a policy to each desired Fusion panel before composition. Cross-panel endpoints are rebuilt after panel measurement; the outer Fusion allocations and its separate relationship guide are not controlled by this policy. Facets and arbitrary annotation grobs are outside the automatic layout contract.
Value
A plot policy added with +. Target-size diagnose_ggchord() results
include adaptive_layout (effective styles and scale factors) and
guide_layout (candidates, constraints, chosen layouts and measured bounds).
A feasible guide layout is not certification of every label or arbitrary
grob. Ordinary layout-only exports report the policy without claiming a
target-device guide arrangement.
Examples
library(dplyr)
seqs <- seq_data_example |>
slice_head(n = 2) |>
select(accver, length)
p <- ggchord(seqs) +
geom_seq() +
geom_seq_label() +
adapt_ggchord(reference_size = c(8, 6))
p
# ggplot2::ggsave("adaptive.png", p, width = 8, height = 6, units = "in")
Coerce a validation result to a flat data.frame
Description
Combines the errors and warnings tables into a single
data.frame and adds a severity column, which is convenient for
filtering, exporting or printing the full report programmatically.
Usage
## S3 method for class 'ggchord_validation'
as.data.frame(x, row.names = NULL, optional = FALSE, ...)
Arguments
x |
A |
row.names |
Ignored. |
optional |
Ignored. |
... |
Ignored. |
Value
A data.frame with columns table, category,
row, column, message and severity.
See Also
Adapt aligned characters with exact source positions
Description
Accepts an existing alignment, never computes one. Equal character counts
are necessary but do not establish homology. Each input character has an
alignment_column; - and . are retained gaps with missing
source_position. Case and ambiguous symbols are retained. Lowercase
characters consume positions: this is not an A3M insertion parser.
Usage
as_ggchord_alignment(sequences, alphabet, source_data = NULL, circular = FALSE)
Arguments
sequences |
Named character vector of aligned strings, or a data frame
with unique |
alphabet |
Explicit |
source_data |
Optional data frame with one row per alignment |
circular |
Explicit logical declaration that every source is circular, default FALSE. Requires source_data with full source_length or full sequence. Coordinates wrap at that length in the declared strand direction; nongap characters may cover at most one complete tour. Adds source_circular and source_length columns. A circular plot never activates this conversion. |
Details
Without source_data, positions count from one in each ungapped input
fragment on the forward strand. They are not complete-genome coordinates.
Optional source metadata declares the first nongap position and direction.
Negative-strand positions decrease. Already aligned strings must be in
alignment orientation: they are never automatically reversed. If a full
source string is supplied, characters are verified against that string;
DNA/RNA use the complement on the negative strand, AA only reverses order.
Missing full source strings mean unverified characters, not invented data.
Value
An ordinary long data frame containing accver, alignment_column,
source_accver, source_position, symbol, is_gap, strand, alphabet,
sequence_unit, source_verified and .source_row. Conversion provenance
retains the original input and normalized source metadata. No identity,
consensus, translation, phase or full sequence length is inferred.
source_verified records whether the record's nongap characters were
checked, including on its gap rows; it is not independent biological
confirmation of the supplied source.
Examples
# Explicit synthetic format example, not a biological alignment claim.
aligned <- as_ggchord_alignment(c(A = "AC-G", B = "ACTG"), "DNA")
aligned
Convert intervals to generic ggchord features
Description
GRanges coordinates are already one-based inclusive and are not shifted.
Strand * is retained as source_strand, while the output uses
strand = "." and directionality = "none". Use the returned table in
geom_feature(data = ...) to preserve nondirectional intervals; geom_gene()
requires directional gene input. No unknown strand is invented as +.
Usage
as_ggchord_feature(x, mapping = NULL)
Arguments
x |
A data frame or |
mapping |
Optional named character vector mapping output roles to
source columns, as in |
Value
An ordinary feature data frame with accver, start, end,
strand, directionality, retained metadata and conversion provenance.
Conflicting metadata names receive a metadata_ prefix; the attribute's
column_map records the output name.
See Also
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
data(gene_data_example)
genes <- gene_data_example |>
transmute(accver, start, end, strand = source_strand)
renamed <- genes |>
rename(chrom = accver, left = start, right = end)
features <- as_ggchord_feature(renamed,
mapping = c(accver = "chrom", start = "left", end = "right")
)
ggchord(seq_data = seqs) +
geom_seq() +
geom_feature(data = features)
Convert paired genomic intervals to ggchord links
Description
For GInteractions, the first stored anchor becomes query and the second
becomes subject. Their order is never sorted or swapped by this adapter.
A source object that already canonicalized its anchors cannot recover their
earlier biological host/virus roles; establish those roles before conversion.
Negative-strand anchor endpoints run from end to start. Unknown-strand
anchors retain increasing coordinates, their * strand and
orientation_known = FALSE; increasing order is not direction evidence.
Interval interactions do not imply a pairwise alignment: identity and
alignment length are not inferred from anchor widths.
Usage
as_ggchord_link(x, mapping = NULL)
Arguments
x |
A data frame or |
mapping |
Optional named character vector mapping canonical link roles
to source columns, as in |
Value
An ordinary data frame with qaccver, saccver, qstart, qend,
sstart, send and source metadata. Paired objects also retain anchor
indices, source row/name, anchor strands, anchor metadata prefixed with
query_/subject_, and object-level metadata in the conversion attribute.
See Also
Examples
library(dplyr)
data(ribbon_data_example)
links <- ribbon_data_example |>
select(qaccver, saccver, qstart, qend, sstart, send)
as_ggchord_link(links)
Convert sequence information to ggchord input
Description
Explicit adapters return ordinary data frames. Optional interval packages are loaded only when their objects are supplied; drawing never installs or runs external data preparation. Supported S4 inputs supplied directly to ggchord or its layers use the same adapters. Identifiers are kept verbatim.
Usage
as_ggchord_seq(x, mapping = NULL, lengths = NULL, ids = NULL)
Arguments
x |
A data frame, |
mapping |
Optional named character vector |
lengths |
Optional named numeric vector of known sequence lengths. Fills unknown lengths and must agree with any known source lengths. |
ids |
Optional character vector of explicit identifiers for unnamed
|
Details
For a GRanges object, lengths come from its Seqinfo, never from the
maximum observed feature endpoint. A GInteractions object uses the same
information from its common regions. Only sequence names used by the
supplied intervals are returned; a Seqinfo object returns all its entries.
Unknown lengths require explicit lengths or corrected source information.
XStringSet and XString inputs use their stored sequence widths.
Set names are identifiers; unnamed sequences require explicit ids.
Explicit IDs must agree with existing nonempty names, so identifiers and
accession versions are never silently rewritten. sequence_unit records
"bp", "aa", or "character"; amino-acid widths are not nucleotide
coordinates. AAString inputs can be plotted directly in native aa coordinates.
Arbitrary character widths remain available for data workflows but are not
accepted by ggchord(). To display protein intervals on a nucleotide
genome instead, use build_ggchord_cds() and project_ggchord_features() or
project_ggchord_links() with known nucleotide sequence lengths.
Empty sequences are rejected like other zero lengths.
Value
An ordinary data frame with accver, length and retained metadata.
Its ggchord_conversion attribute records input class, coordinate system,
column renaming, object-level metadata, and upstream import/conversion
provenance when present. No genomic coordinates or
accession versions are guessed or rewritten.
See Also
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
renamed <- seqs |>
rename(chrom = accver, size = length)
as_ggchord_seq(renamed, mapping = c(accver = "chrom", length = "size"))
Build an explicit spliced CDS coordinate map
Description
Builds a mapping from observed protein residues to genomic coding bases.
CDS rows sharing feature_id form one coding model. Their genomic intervals
must be non-overlapping and have one sequence and known strand. Segments are
ordered in transcription direction, increasing on + and decreasing on -.
An explicit segment_order overrides genomic sorting, allowing a declared
circular-origin join. A segments list-column can declare segment_order
for transcription order, including reverse-strand and origin joins; otherwise
its pieces follow genomic strand order. Generic segment_index identifiers
are preserved as source metadata and do not define transcription order. Nested
phases may be supplied or derived from an explicit first phase or
codon_start - 1; no phase is guessed from the genomic envelope.
Trans-spliced models spanning different sequence IDs are rejected.
Usage
build_ggchord_cds(cds_data, genetic_code = NULL, partial = c("error", "trim"))
Arguments
cds_data |
Data frame with |
genetic_code |
Optional positive integer code ID, scalar or named by
CDS |
partial |
|
Details
GFF3 phase counts bases from a segment's biological 5-prime end to the
next codon boundary. Only the first phase is skipped; later phases validate
the accumulated coding length, retaining bases of codons split across exons.
partial = "error" rejects partial ends. Explicit "trim" permits a
nonzero first phase, partial-end flags and incomplete terminal codons, and
excludes bases without complete codons. Residue one then means the first
complete observed codon, not an inferred position in an unobserved protein.
Optional partial5, partial3, genetic_code, and protein_id columns
must agree within each model. A nonzero initial phase requires partial5;
if absent it is recorded as partial5. A terminal remainder similarly records
partial3 unless a conflicting explicit flag is supplied. Genetic-code IDs
are retained as metadata: coordinate projection does not translate sequence,
identify stop codons, or infer a genetic code. codon_count includes any
source terminal stop codon. Frameshifts, ribosomal slippage and translation
exceptions or non-join location operators cannot be represented by a simple
triplet map and are rejected
when declared. No full protein length or identity is inferred.
Value
A ggchord_cds list containing a models summary, transcription-
ordered segments per feature, original source_data and provenance.
Segment cds_start/cds_end identify complete-codon nucleotide positions;
genomic coordinates and original row numbers remain available.
See Also
https://github.com/The-Sequence-Ontology/Specifications/blob/master/gff3.md
Examples
library(dplyr)
data(plasmid_example_pUC19)
feature_source <- find_common_features(plasmid_example_pUC19)
features <- feature_source |>
select(accver, start, end, strand, type, anno)
coding <- features |>
filter(anno == "AmpR", type == "CDS") |>
select(accver, start, end, strand) |>
mutate(feature_id = paste(accver, "AmpR", sep = ":"), phase = 0)
cds <- build_ggchord_cds(coding, genetic_code = 11)
cds$features
Bundle dense alignment ribbons explicitly
Description
Aggregates nearby alignment ribbons on a normalized query/subject grid.
Bundling is always explicit: geom_link_ribbon() continues to draw one
ribbon per input row unless the returned data are supplied by the user.
Groups use relative endpoint direction, so reversing both ends can remain
in the same group. The envelope follows the first row's absolute directions;
length and identity are length-weighted source means (length is rounded),
not statistics of a newly computed alignment. Conflicting extra metadata
become typed missing values. Use group_by to keep source categories
separate and retain the original input with the source-row report.
Single-base endpoint rows stay independent because their endpoint order
cannot define an absolute aggregate direction. Density can still count
them without merging their geometry.
Usage
bundle_ggchord_ribbons(
ribbon_data,
seq_data,
bins = 80L,
min_bundle = 2L,
weight = c("length", "count", "pident"),
group_by = NULL
)
Arguments
ribbon_data |
Alignment data in ggchord ribbon format. |
seq_data |
Sequence data containing |
bins |
Positive integer number of normalized midpoint bins per sequence, default 80. |
min_bundle |
Minimum number of rows required for aggregation, default 2. Smaller groups remain as individual ribbons. |
weight |
Bundle weight: |
group_by |
Optional character columns that must agree before ribbons can be bundled. |
Value
A list with data and report. The data include
.bundle_n, .bundle_weight, and .bundle_density; the
report maps each output row back to its source rows.
See Also
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
data(ribbon_data_example)
links <- ribbon_data_example |>
select(qaccver, saccver, qstart, qend, sstart, send, pident, length)
out <- bundle_ggchord_ribbons(links, seqs, bins = 30)
out$report
Clean ggchord input data with explicit, report-driven policies
Description
Applies a conservative, predictable set of cleaning policies to the three
ggchord tables and returns the cleaned copies plus a full report. The
original data frames are never modified. Nothing is dropped silently: every
change (including every dropped row) is recorded in report with the
original row number, the reason, the original value(s) and the new value(s).
Its default sorting policy differs from preparation's
direction-preserving default. Use reversed_interval = "keep" for
directional links and circular-origin features; sorting endpoints loses
information that a later workflow cannot reconstruct.
Usage
clean_ggchord_data(
seq_data,
ribbon_data = NULL,
gene_data = NULL,
unknown_id = c("drop", "error", "keep"),
out_of_range = c("clip", "drop", "error", "keep"),
reversed_interval = c("sort", "drop", "error", "keep"),
invalid_pident = c("clip", "drop", "error", "keep"),
empty_annotation = c("keep", "drop", "replace"),
replacement_annotation = "unannotated",
feature_data = NULL
)
Arguments
seq_data |
data.frame/tibble, required. Must contain |
ribbon_data |
data.frame/tibble or |
gene_data |
data.frame/tibble or |
unknown_id |
Character, default |
out_of_range |
Character, default |
reversed_interval |
Character, default |
invalid_pident |
Character, default |
empty_annotation |
Character, default |
replacement_annotation |
Character, default |
feature_data |
Unified annotation input; mutually exclusive with gene_data. |
Value
A list with four components: seq_data, ribbon_data,
gene_data (cleaned copies) and report (a data.frame with
columns table, row (original row number), column,
reason, original_value, new_value and
action).
See Also
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
data(ribbon_data_example)
links <- ribbon_data_example |>
select(qaccver, saccver, qstart, qend, sstart, send, pident, length)
# Deliberate diagnostic error in a copy; source observations remain unchanged.
problem <- links |>
slice_head(n = 2) |>
mutate(qaccver = replace(qaccver, 2, "absent"))
cleaned <- clean_ggchord_data(seqs, problem, unknown_id = "drop")
cleaned$report
Chord diagram coordinate system
Description
Controls global rotation, aspect ratio, coordinate limits, clipping and the strategy used to fit chord geometry and labels.
Usage
coord_chord(
rotation = 0,
ratio = 1,
xlim = NULL,
ylim = NULL,
expand = FALSE,
clip = "off",
fit = c("labels", "geometry", "manual")
)
Arguments
rotation |
Global counterclockwise layout rotation in degrees, default 0, measured from the positive x axis. This rotates the complete layout; it does not change the biological strand or sequence orientation. |
ratio |
Fixed y/x aspect ratio, default 1. |
xlim, ylim |
Optional user limits. Explicit limits take priority over automatically fitted limits. |
expand |
Logical. Expand coordinate limits, default FALSE. Automatic fitting already includes a small safety margin; set TRUE to request the additional ggplot2 coordinate expansion. |
clip |
Whether drawing is clipped to the panel, default |
fit |
Fitting strategy: |
Value
A Coord object for ggplot2 + composition
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
ggchord(seq_data = seqs) +
geom_seq() +
coord_chord(rotation = 20)
Single-sequence circular coordinate system
Description
Single-sequence circular coordinate system
Usage
coord_circular(
rotation = 0,
direction = c("clockwise", "counterclockwise"),
gap = 0,
ratio = 1,
xlim = NULL,
ylim = NULL,
expand = FALSE,
clip = "off",
fit = c("labels", "geometry", "manual")
)
Arguments
rotation |
Counterclockwise rotation in degrees from a 12-o'clock genomic origin. The default 0 keeps the origin at 12 o'clock; 90 places it at 9 o'clock, and -90 at 3 o'clock. |
direction |
Direction of increasing genomic coordinates. |
gap |
Opening in degrees. Zero draws a closed circle. |
ratio |
Fixed y/x aspect ratio, default 1. |
xlim, ylim |
Optional user limits. Explicit limits take priority over automatically fitted limits. |
expand |
Logical. Expand coordinate limits, default FALSE. Automatic fitting already includes a small safety margin; set TRUE to request the additional ggplot2 coordinate expansion. |
clip |
Whether drawing is clipped to the panel, default |
fit |
Fitting strategy: |
Value
A Coord object for ggplot2 composition.
Linear multi-sequence collinearity coordinates
Description
Draws sequences as left-aligned horizontal backbones, ordered from top to
bottom by geom_seq(seq_order = ...). All sequences share one linear sequence-unit
scale. seq_orientation = -1 reverses a sequence together with its features,
links and axis without modifying the input data.
Usage
coord_collinear(
ratio = 1,
xlim = NULL,
ylim = NULL,
expand = FALSE,
clip = "off",
fit = c("labels", "geometry", "manual"),
align = c("left", "center", "right"),
anchor = NULL,
orientation = c("manual", "auto"),
min_support = 0.1,
segments = NULL,
segment_gap = 100,
seq_axis = c("horizontal", "vertical")
)
Arguments
ratio |
Fixed y/x aspect ratio, default 1. |
xlim, ylim |
Optional user limits. Explicit limits take priority over automatically fitted limits. |
expand |
Logical. Expand coordinate limits, default FALSE. Automatic fitting already includes a small safety margin; set TRUE to request the additional ggplot2 coordinate expansion. |
clip |
Whether drawing is clipped to the panel, default |
fit |
Fitting strategy: |
align |
Display alignment: |
anchor |
Optional anchor positions as a numeric vector named by
|
orientation |
|
min_support |
Minimum directional imbalance in |
segments |
Optional data frame with unique window |
segment_gap |
Positive display gap in native sequence units when |
seq_axis |
|
Details
In this coordinate system, geom_seq(seq_gap = ...) specifies the distance
between consecutive backbones as a proportion of the longest backbone's
width (default 0.3). Positive Position offsets point upward and negative
offsets downward, independently of sequence orientation. Sequence labels
appear to the left of their backbone. Automatic feature labels use local
horizontal rows; fixed radial labels are vertical and tangent labels are
horizontal. Label side "outside" means above and "inside" below.
Explicit sequence radius, curvature, ring mappings/scales and sequence-label
radius cannot be converted and produce an error. Remove these arguments
when switching from coord_chord(). Primer, restriction-site and centre-label
layers are unsupported here; use coord_circular() for single-sequence maps
or geom_feature() for general linear annotations. Single-sequence chord
compositions remain available. Cross-track links may cross intervening tracks.
Explicit link control points use the exported linear layout x/y units;
the longest backbone has width 2 (the longest complete display row when
segments is supplied).
The circular external = FALSE feature-label constraint cannot be converted;
remove it to use linear label rows. Gene/feature repel layout modes share
the linear row strategy rather than selecting circular label tracks.
align and anchor control a reversible display translation. With no
anchor, the selected edge or centre of each complete sequence is placed at
x = 0. With an anchor, the selected edge or centre of each anchor interval
is placed at x = 0 instead. Left and right refer to the displayed interval,
after orientation has been applied. Genomic input coordinates stay unchanged.
Sequence order is never changed by alignment or automatic orientation.
orientation = "auto" evaluates interval links against earlier displayed
sequences and chooses the direction supported by the larger aligned-interval
weight. The first sequence fixes the reference direction. Ambiguous,
insufficiently supported and unconnected sequences retain their initial
direction, with evidence recorded in the exported layout diagnostics. This
is a display heuristic, not a biological strand assignment or a guarantee
of a global optimum. It cannot be combined with an explicit
geom_seq(seq_orientation = ...).
With segments, each accession remains an independent window but windows
sharing row_id occupy one display row. Their table order is left to right;
align applies to the whole row. segment_gap reserves display space in native
sequence units, independently of omitted genomic length. Internal ends receive
break marks. Use segment_ggchord_data() to crop/split input first. Local
reversal comes from the table's orientation, so automatic orientation,
explicit sequence orientation and anchor conflict with this mode. Ribbon
adjacency follows display rows; same-row ribbons are omitted with a report,
and explicit same-row pairs or point links are unsupported.
Value
A ggplot2 Coord object for composition with a ggchord plot.
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
data(ribbon_data_example)
links <- ribbon_data_example |>
select(qaccver, saccver, qstart, qend, sstart, send)
ggchord(seq_data = seqs, ribbon_data = links) +
geom_seq() +
geom_link_ribbon() +
geom_seq_label() +
coord_collinear(orientation = "auto")
Two-axis HSP Dotplot coordinates
Description
Query positions occupy x and subject positions occupy y. Each axis has
independently ordered sequence segments, optionally reversed for display.
Coordinates are one-based positions in native sequence units (bp or aa).
Concatenation gaps are display spacing, not omitted biological sequence.
No sequence backbone layer is required. Use geom_alignment_segment() to
display HSPs; other ggchord geometries and facets are not yet supported.
Standard ggplot2 annotations and explicit position scales remain available.
Usage
coord_dotplot(
x_seqs = NULL,
y_seqs = NULL,
x_orientation = 1,
y_orientation = 1,
gap = NULL,
ratio = 1,
xlim = NULL,
ylim = NULL,
expand = FALSE,
clip = "on"
)
Arguments
x_seqs, y_seqs |
Optional unique accession vectors in axis order. Defaults to the query/subject accessions occurring in alignment layers, or all sequences when there are no alignments. Rows outside a selected axis set are omitted and recorded; self and repeated HSP rows are retained. |
x_orientation, y_orientation |
Display direction: 1 or -1, either a scalar or a vector named by every selected accession. Input is unchanged. |
gap |
Nonnegative spacing in native sequence units between axis
segments. |
ratio |
Ratio of physical y units to physical x units, default 1. |
xlim, ylim |
Optional global concatenated position limits. These zoom the panel without changing exported HSP endpoints. |
expand |
Logical. Expand panel limits, default FALSE. |
clip |
Panel clipping, |
Value
A ggplot2 Coord object.
Examples
data(seq_data_example)
data(ribbon_data_example)
ggchord(seq_data_example, ribbon_data_example) +
geom_alignment_segment() +
coord_dotplot()
Radial spokes for multi-sequence synteny
Description
Displays linear sequences as equally spaced outward spokes. Adjacent spokes, including the last and first, may be joined by existing interval alignments. No missing relationship is created. Two spokes display each input HSP once; one spoke is not a multi-sequence synteny view.
Usage
coord_radial_synteny(
start_angle = 90,
clockwise = TRUE,
inner_radius = 0.6,
ratio = 1,
xlim = NULL,
ylim = NULL,
expand = FALSE,
clip = "off",
fit = c("labels", "geometry", "manual"),
nonadjacent_bulge = 0
)
Arguments
start_angle |
Direction of the first outward spoke in degrees, counterclockwise from the positive x axis. Default 90 starts at noon. |
clockwise |
Logical, order subsequent spokes clockwise, default TRUE. |
inner_radius |
Positive inner radius in layout units, default 0.6. The longest proportional spoke has length 2. The central hole is display spacing and does not remove any source positions. |
ratio |
Fixed y/x aspect ratio, default 1. |
xlim, ylim |
Optional user limits. Explicit limits take priority over automatically fitted limits. |
expand |
Logical. Expand coordinate limits, default FALSE. Automatic fitting already includes a small safety margin; set TRUE to request the additional ggplot2 coordinate expansion. |
clip |
Whether drawing is clipped to the panel, default |
fit |
Fitting strategy: |
nonadjacent_bulge |
Non-negative outward lift at the midpoint of
nonadjacent annular ribbons, in layout units (the longest proportional
spoke has length 2). Default 0 retains the original path. The lift and its
slope vanish at both endpoints. Adjacent ribbons and point links are
unchanged. A positive lift also separates overlapping nonadjacent ribbon
midpoints in the same channel, retaining their individual interval widths;
this does not eliminate crossings forced by source endpoint order.
Explicit |
Details
Uses the same sequence, feature, track, label and link layers as
coord_collinear(). geom_seq(seq_order = ...) orders spokes and declares
named repeated display instances; ambiguous relationships require between.
Lengths are proportional by default; geom_seq(length_mode = "equal")
explicitly normalizes display lengths while retaining native positions.
Positive feature/track offsets point counterclockwise from each outward
spoke, independently of biological direction and display order. Sequence
names are placed just beyond the outer ends to keep the central hole clear.
Ribbons default to cyclic neighbors. Use explicit pairs or
adjacent_only = FALSE for nonadjacent ribbons; point links to nonneighbors
require explicit between. Adjacent ribbon outlines are solid; nonadjacent
outlines are dashed, following the final cyclic spoke order. Explicit fixed
or mapped line types take priority. Default curved connections stay in an annular
channel, retaining the complete interval fronts and inversion twists.
Explicit control points use final layout x/y units. Shared link branches,
circular-only annotations, shared straight scale bars and joined multi-window
rows are unsupported. Use the native position axis on each spoke.
Interval fronts use closed one-based interval boundaries
[min(start,end)-1, max(start,end)] in input direction. A one-position
interval retains nonzero width. Axis ticks and position mapping use
one-based positions; this new view does not change existing view conventions.
Value
A ggchord coordinate object.
Examples
data(seq_data_example)
data(ribbon_data_example)
ggchord(seq_data_example, ribbon_data_example) +
geom_seq() +
geom_link_ribbon() +
geom_seq_label() +
coord_radial_synteny(start_angle = 90, inner_radius = 0.7)
Mirrored two-column genomic interval relationships
Description
Each source sequence appears once in each column. Input query intervals connect from the left to subject intervals on the right; input reciprocal records remain distinct. This is not a multistage flow or a conservation law. Source lengths and both HSP endpoints determine the displayed interval widths.
Usage
coord_sankey(
column_gap = 3,
self_links = FALSE,
ratio = 1,
xlim = NULL,
ylim = NULL,
expand = FALSE,
clip = "off",
fit = c("labels", "geometry", "manual")
)
Arguments
column_gap |
Positive separation of the two backbones in layout units. |
self_links |
Show relationships whose query and subject entity are equal. |
ratio |
Fixed y/x aspect ratio, default 1. |
xlim, ylim |
Optional user limits. Explicit limits take priority over automatically fitted limits. |
expand |
Logical. Expand coordinate limits, default FALSE. Automatic fitting already includes a small safety margin; set TRUE to request the additional ggplot2 coordinate expansion. |
clip |
Whether drawing is clipped to the panel, default |
fit |
Fitting strategy: |
Value
A ggchord coordinate object.
Examples
# Synthetic intervals illustrate the mirrored layout.
s <- data.frame(accver = c("A", "B"), length = c(1000, 600))
h <- data.frame(qaccver = "A", saccver = "B",
qstart = 100, qend = 300, sstart = 50, send = 250)
ggchord(s, h) + geom_seq() + geom_link_ribbon() +
geom_seq_label() + coord_sankey()
Deduplicate alignment ribbons
Description
Removes fully duplicated, coordinate-near-duplicated or highly overlapping
alignment blocks within each (query, subject) pair and keeps the best
representative per keep.
Usage
deduplicate_ggchord_ribbons(
ribbon_data,
tolerance = 0,
by = c("exact", "coordinates", "overlap"),
keep = c("best_pident", "longest", "first"),
min_reciprocal_overlap = 0.9
)
Arguments
ribbon_data |
data.frame in ribbon_data format. |
tolerance |
Numeric, default 0. Maximum absolute difference (in bp)
allowed on each of |
by |
Character, default |
keep |
Character, default |
min_reciprocal_overlap |
Numeric (0-1), default 0.9. Reciprocal overlap
threshold used with |
Value
A list with data (deduplicated data frame with
source_rows attribute) and report (n_input/n_kept/n_removed
plus a data.frame of removed rows with row, duplicate_of and
reason).
See Also
Examples
library(dplyr)
data(ribbon_data_example)
links <- ribbon_data_example |>
select(qaccver, saccver, qstart, qend, sstart, send, pident, length)
out <- deduplicate_ggchord_ribbons(links, by = "overlap")
out$report
Inspect one target-size render without changing the plot
Description
Builds on a temporary device of the requested kind and measures the actual
single panel after gtable layout, then refines physical geometry within a
bounded render-local context. The original plot and its layout cache are
left unchanged. Standard saving continues to use ggplot2::ggsave().
Usage
diagnose_ggchord(
plot,
width = 7,
height = 5,
units = c("in", "cm", "mm", "px"),
device = c("png", "pdf", "svg"),
dpi = 144,
min_size = 2,
min_linewidth = 0.2,
colour_vision = FALSE
)
Arguments
plot |
A ggchord plot. |
width, height |
Positive target canvas dimensions. |
units |
Dimensions in |
device |
Target device: |
dpi |
Raster resolution; also defines pixel dimensions. |
min_size, min_linewidth |
Advisory minimum text size and line width, both in millimetres. These do not modify the supplied style. |
colour_vision |
Request optional simulated colour-vision hints. |
Details
Results describe evidence, not a general quality certificate. Checks cover
registered vertex bounds, measured text, small text/lines, oversized guides,
and existing label/track diagnostics. Objects outside a panel with
clip = "off" are legal when they still fit the canvas. Unregistered custom
grobs, arrowhead extents, font embedding/fallback and cross-application
transparency are not certified. Device warnings remain in the report.
Grayscale suggestions compare luminance of opaque discrete mapped colours
(difference below 0.05); continuous gradients are deliberately excluded.
With colour_vision = TRUE, optional colorspace public simulations for
protan/deutan/tritan at severity 1 in linear RGB flag Lab distances below 10.
These heuristic thresholds ignore spatial context, alpha compositing and
viewing conditions, and never automatically change the plot or fail a run.
Value
A ggchord_diagnostics list with measurement, checks, text and
guide measurements, colour suggestions, existing label_diagnostics,
annotation_registry, track_registry, track_diagnostics, and captured
device warnings. Field units and provenance are described in
ggchord_layout_contract. measurement$status concerns panel measurement only;
it never means that all quality or portability checks passed.
Label quality
label_quality reports summary counts, text-object conflicts, registered
annotation polylines and measured oriented text boxes in millimetres. Its
measurement entry separates panel measurement, geometry convergence and
physical refinement passes. Circular calibration may try one extrapolated
scale, accepting it only after the usual measured convergence gate passes;
rejected trials retain the ordinary refinement sequence. Drawing warns when
bounded physical refinement does not converge; diagnostics capture that
warning and retain the physical_layout check. Arc
glyphs belonging to one string are one text object; their intentional
internal contacts are not label collisions. Leader crossings exclude shared
endpoints; through-text checks concern box interiors, not exact glyph ink.
Source-label visibility follows the layer policy and may share one displayed
label across records. It is distinct from the number of text/glyph boxes.
Registered gene/feature polygon envelopes are checked against text boxes;
feature_contacts separates proven own-source placement, other-source
contacts and unresolved associations. Transparent polygons remain in this
conservative geometry check. Non-polygon strokes/markers and visibility or
occlusion are not checked; feature_parts_unchecked records skipped parts.
Unregistered/outer decorations remain unchecked. These measurements never
move, hide or change input records.
Degenerate annotation placeholders with coincident endpoints are not
counted as leaders. Circular label visibility can additionally report
leader_text_status for clear, detoured or unresolved static-text routes.
leader_route_status records bounded crossing detours or unresolved routes
while preserving directed endpoints and source-label positions.
axis_clearance records available automatic circular label decisions and
radial shifts in millimetres, positive outward and negative inward.
Composite site labels use the same bold name and regular coordinate
fragments, physical gap and text styles as the renderer.
Guide measurements
guide_measurements records active roles, titles, item counts, device text
widths/heights, requested key sizes, direction, grid and shared side budget.
These complement actual guide-box measurements; requested key dimensions
are not claimed as final grob bounds. Font fallback remains uninspected.
With adapt_ggchord(), adaptive_layout reports effective theme styles,
selected default fixed geom line widths and scale factors. In adaptive mode,
guide_layout reports the bounded joint
search, selected guide grids/positions, explicit locks and measured guide-box
bounds in mm. feasible concerns the guide canvas and reserved panel budget;
it does not certify every label or custom grob. insufficient_space retains
all categories and reports the failure instead of silently shrinking text.
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
p <- ggchord(seq_data = seqs) +
geom_seq()
diagnose_ggchord(p, width = 8, height = 6, units = "in", device = "png")
Export a Fusion at a specified physical size
Description
Builds at the requested size on a temporary measurement device, restoring the previous device. Geometry reflects that device's font metrics. A later save rebuilds on its actual output device, so minor metric differences are possible. Source coordinates and identities remain unchanged.
Usage
export_ggchord_fusion(plot, width = 10, height = 8)
Arguments
plot |
A Fusion object. |
width, height |
Positive canvas dimensions in inches. |
Value
A list with panels, instances, connections, fronts, paths,
diagnostics and per-panel source layouts. Compositions made with
magnify_ggchord() also populate focus_region_data, focus_regions, focus_fronts and decorative
leaders; ordinary Fusion objects return empty tables for these fields.
Nested leaves use full paths such as detail/center. Composition-scoped
focus_region_data_by_composition preserves all original region tables;
focus_frame_region_data and focus_frame_region_data_by_composition retain
explicit source-frame overrides separately from the real selected intervals.
composition_id plus region_row identifies their derived rows. Containers
have coordinate = fusion and are not biological interval namespaces.
overlaps reports deliberate covering order. source_observations counts
display copies only for explicit source_hsp_id; no identity is inferred
by comparing values. Requested boxes/angles and resolved allocations remain
in panels. All global geometry uses mm. routing_obstacles records measured
physical envelopes; routing_corridors records explicit shared display
channels and their source-row members. Connections/leaders report route
status and collisions. leader_paths stores decorative polyline vertices.
These routes do not imply a global optimum or altered biological evidence.
metadata includes final outer guide_bounds_mm/guide_sizes_mm and the
guide_layout candidate/constraint report; per-guide native positions remain
independent. Native composition decorations add content_bounds_mm and
content_canvas_mm plus plot_decoration with effective labels and physical
envelopes; source coordinates and rows remain unchanged. Nested composition
reports also appear in diagnostics.
Examples
data(seq_data_example)
p <- ggchord(seq_data_example) + geom_seq()
f <- ggchord_fusion(p) + fusion_panel(p + coord_collinear(), "detail")
export_ggchord_fusion(f, width = 10, height = 8)$panels
Export computed ggchord geometry
Description
Builds a ggchord plot and returns selected computed geometry in a stable,
layer-aware structure. Every exported row records its source layer and,
where applicable, its source input row. Original mapped columns already
attached to the geometry are preserved.
This is the recommended interface for consuming layout tables;
get_chord_layout() remains available for the complete layout list.
Both retain their documented fields. See ggchord_layout_contract for
units, provenance and stability boundaries.
Usage
export_ggchord_layout(
plot,
include = c("seq", "ribbon", "gene", "feature", "labels", "axis", "track"),
original_data = FALSE
)
Arguments
plot |
A ggchord plot. |
include |
Character vector selecting any of |
original_data |
Logical. Include the resolved per-layer input tables
under |
Value
An object of class ggchord_layout_export. Selected component
names contain data frames. Circular layouts additionally contain an
annotation_registry data frame. Its inner rows expose the physical
track, radial width and boundaries; outer rows expose region, sector,
annotation class, dominant and actual band, spill reason, leader-crossing
count, slot, bounding box and leader corridor.
Explicitly inside primer and restriction callouts
register measured inner boxes rather than exterior bands or slots.
The metadata member
records rotation, aspect ratio, limits, native sequence_unit (bp/aa), and
transformation state.
Collinear layouts instead include sequence_layout, containing each
sequence's horizontal range, backbone y, orientation, units_per_position,
and sequence_unit. The compatibility field units_per_bp is NA for aa. It also records
reversible x offset, anchor and source origin. orientation_diagnostics
records directional support, confidence and unresolved cases.
Position lanes remain local offsets and are not circular physical tracks.
Their label_diagnostics records placed or hidden labels after shared
linear collision handling, including source layer, row, reason and leader
collisions. connection_report records retained and omitted ribbon input
rows with a selection reason. When converted inputs are present,
conversion_reports retains their conversion attributes, including source
class, column renaming, sequence information and object metadata.
Sequence break marks are included under seq.
Segmented linear displays retain one sequence_layout row per window,
including row_id, segment order, break flags and display gap_bp.
Source accession, origin/end/full length, local orientation, x offset and
units per bp describe each reversible piece; gaps have no source mapping.
Automatic segment break paths have .decoration = "segment_break" in
the sequence geometry. gap_bp is display spacing, not omitted length.
Quantitative geometry is selected with track; track_registry records
each ID/sequence band, source layers, numerical limits, unit and physical
measurement status. track_diagnostics records retained/missing/clipped
source rows. Numerical track axes and explicit bp reference bars are
included under axis; axis_selection records selected sequence axes.
Explicit label shrinking adds label_fit_diagnostics, preserving original
text, requested/minimum/final sizes and fallback or hiding reasons.
render_context distinguishes layout-only estimates from actual panel
measurements. For a target-size measured report use diagnose_ggchord().
source_registry and layer_sources retain constructor and per-layer
annotation identities without overwriting user columns. Explicit layer
tables/functions have layer-local source scope. annotation_duplicates
reports shared constructor rows drawn by multiple geometry layers.
New coordinate fields
Radial synteny layouts include radial_frames (tangent/normal, angle,
local origin and inner radius; theta is in radians) and radial_endpoints (full HSP fronts).
Metadata records cyclic adjacency, display rotation and closed one-based
interval boundaries; these never imply a biological sequence closure.
Dotplots include independent axis_layout frames and original endpoint
rows under alignment; axis selection and unknown directions appear in
connection_report.
Ribbon drawing
ribbon_rendering records per-layer fill/tip mode. Exported polygon fronts
retain the full source intervals. An optional subject tip is decorative;
its shoulder translates the target endpoint span to 88 percent of the
channel. Continuous fills use a device-resolved raster mesh and vector
outlines. A bounded fill budget warns when dense layers reduce resolution.
Examples
library(dplyr)
library(ggchord)
data(seq_data_example)
data(ribbon_data_example)
p <- ggchord(seq_data_example, ribbon_data_example) +
geom_seq() +
geom_link_ribbon()
exported <- export_ggchord_layout(p, include = c("seq", "ribbon"))
names(exported)
Filter alignment ribbons before plotting
Description
Keeps the ribbon rows that satisfy all requested criteria and optionally
sorts them. The returned data frame keeps every extra column and the
original column order; the original row numbers are attached as the
source_rows attribute.
Each non-NULL numeric threshold must be one finite number. Columns used by
a numeric criterion must be numeric; missing values fail that criterion.
Usage
filter_ggchord_ribbons(
ribbon_data,
seq_ids = NULL,
min_pident = NULL,
max_pident = NULL,
min_length = NULL,
max_evalue = NULL,
min_bitscore = NULL,
min_query_coverage = NULL,
min_subject_coverage = NULL,
keep_pairs = NULL,
drop_self_links = TRUE,
sort_by = NULL
)
Arguments
ribbon_data |
data.frame with at least |
seq_ids |
Optional character vector. Keep only rows where both the
query and the subject are in |
min_pident, max_pident |
Optional numeric. Lower/upper bounds on
|
min_length |
Optional numeric. Lower bound on |
max_evalue |
Optional numeric. Upper bound on |
min_bitscore |
Optional numeric. Lower bound on |
min_query_coverage |
Optional numeric (0-100). Lower bound on the query
coverage. Uses the |
min_subject_coverage |
Optional numeric (0-100). Lower bound on the
subject coverage, computed from |
keep_pairs |
Optional data.frame/list/matrix describing an undirected set of sequence pairs. A data.frame or matrix with the first two columns used as query/subject IDs, or a list of length-2 character vectors. A row is kept when its query/subject pair matches any pair in either direction. |
drop_self_links |
Logical, default |
sort_by |
Optional character vector of column names. Prefix a name
with |
Value
A list with data (the filtered data frame, with
source_rows attribute) and report (n_input/n_kept/n_removed,
removed_by_reason, removed_rows and kept_rows).
See Also
Examples
library(dplyr)
data(ribbon_data_example)
links <- ribbon_data_example |>
select(qaccver, saccver, qstart, qend, sstart, send, pident, length)
out <- filter_ggchord_ribbons(links, min_pident = 95, min_length = 500)
out$report
Filter restriction sites for display
Description
Filter restriction sites for display
Usage
filter_restriction_sites(
sites,
set = c("all", "unique", "unique_dual", "six_plus", "unique_6plus", "commercial",
"reference"),
enzymes = NULL,
min_site_length = NULL,
cuts = NULL,
window = NULL,
commercial_only = FALSE,
parent_set = c("all", "commercial_all", "commercial_nonredundant")
)
Arguments
sites |
Result from |
set |
Display preset. |
enzymes, min_site_length, cuts, window, commercial_only |
Additional filters. |
parent_set |
Enzyme catalogue subset. |
Value
A row subset whose biological coordinates are unchanged.
See Also
Examples
data(plasmid_example_pUC19)
sites <- find_restriction_sites(plasmid_example_pUC19,
enzymes = c("EcoRI", "BamHI", "HindIII"))
unique_sites <- filter_restriction_sites(sites, set = "unique")
Find common biological features in DNA sequences
Description
Searches the built-in common-feature database (or a compatible custom
database) using curated exact-sequence annotations, exact DNA, and the
detection mode stored for each database record. Restriction sites are
intentionally outside this API; use
find_restriction_sites() for those.
Protein matching uses a standard-code six-frame translation, without
alternative initiation, splicing or origin-crossing protein matches.
Source geneticCode metadata does not select a translation table. For
nonstandard codes use mode = "dna" or external code-aware analysis.
confidence is a deterministic heuristic label, not a probability or
experimental confirmation. identity and coverage describe the reported
match method, not independently validated biological function.
Usage
find_common_features(
sequence,
database = NULL,
types = NULL,
features = NULL,
circular = TRUE,
mode = c("auto", "dna", "protein"),
min_protein_identity = 0.9,
min_protein_coverage = 0.8,
resolve = c("best", "all")
)
Arguments
sequence |
DNA text, a named character vector, or a data frame with
|
database |
Optional normalized database list or custom data frame. |
types, features |
Optional feature-type and feature-name/ID filters. |
circular |
Search across the sequence origin. |
mode |
Matching mode. |
min_protein_identity, min_protein_coverage |
Approximate protein
thresholds, each one finite number in |
resolve |
Return deterministic best annotations or every candidate. |
Value
A data frame directly usable by geom_feature() and
geom_feature_label_repel(). feature_class and feature_shape provide
semantic metadata and a geometry hint; neither affects radial stacking.
Explicit user aesthetics and scales still take priority. Its segments list-column
preserves the biological feature's segment structure.
See Also
Find genomic loci around explicitly identified features
Description
Selects targets by feature_id and expands their genomic bounds using
biological upstream/downstream directions. For a negative-strand target,
upstream extends towards larger genomic coordinates. Unknown or
bidirectional strands require equal upstream and downstream distances.
Windows are clipped to the known full sequence length; clipping is reported.
Usage
find_ggchord_loci(
seq_data,
feature_data,
targets,
upstream = 0,
downstream = 0
)
Arguments
seq_data |
Sequence table containing unique |
feature_data |
Feature table containing |
targets |
Non-empty character vector of distinct |
upstream, downstream |
Single non-negative integer numbers of bases added before and after each target in its biological direction. |
Details
Repeated rows with the same feature_id represent segments of one target
and must belong to the same sequence and strand. Their outer bounds define
the target window. Different targets always produce separate windows,
including overlapping targets on the same sequence. No intervening sequence
is removed, concatenated or locally reversed. Ordered one-based inclusive
genomic coordinates are required; origin-spanning circular features and
protein coordinates need an explicit conversion before this operation.
The returned locus_id equals target_id. Pass the returned table as
loci to focus_ggchord_data() to create independent focused sequences
named by those IDs, including multiple windows from one source sequence.
Value
An ordinary data frame in target order with target_id, locus_id,
accver, start, end, strand, unexpanded target_start and
target_end, requested extensions, and clipped_left/clipped_right.
The target_source_rows list column identifies feature input rows used
for each target. Coordinates refer to the supplied sequence table; no
implicit change from focused coordinates to an earlier source is made.
See Also
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
data(gene_data_example)
genes <- gene_data_example |>
transmute(accver, start, end, strand = source_strand)
genes <- genes |>
mutate(feature_id = paste(accver, start, end, sep = ":"))
find_ggchord_loci(seqs, genes, targets = genes$feature_id[1], upstream = 100, downstream = 100)
Find sequencing-primer binding sites
Description
Searches each distinct oligonucleotide once on both target strands and then
attaches all catalogue aliases. Exact matching is the default. Optional
three_prime matching uses the longest exact 3-prime suffix available, with
no mismatches, and is intended for inspecting partial annealing rather than
silently treating it as a full match.
Binding hits are sequence-search results, not experimental validation.
melting_temperature uses the Wallace composition estimate unless source
annotations supply it; ambiguous bases do not contribute to that estimate.
Usage
find_primer_bindings(
sequence,
primers = NULL,
set = c("universal", "all", "reference"),
match = c("exact", "three_prime"),
min_annealed_bases = 15L,
circular = TRUE,
unique_only = FALSE
)
Arguments
sequence |
DNA text, a named character vector, or a data frame with
|
primers |
Optional custom primers with |
set |
Bundled catalogue subset. |
match |
Full exact matching or longest exact 3-prime annealing. |
min_annealed_bases |
One finite integer of at least 8, the minimum
suffix length for |
circular |
Allow matches to cross the sequence origin. |
unique_only |
Keep only primer sequences with one binding site per target. |
Value
One row per binding site. The aliases list-column preserves every
catalogue name associated with the matched oligonucleotide.
See Also
Examples
target <- c(circle = "TTGCAAAAACG")
find_primer_bindings(
target, primers = c(test = "ACGTTGCA"),
min_annealed_bases = 8
)
Find restriction pattern matches and cleavage coordinates
Description
Find restriction pattern matches and cleavage coordinates
Usage
find_restriction_sites(
sequence,
enzymes = NULL,
patterns = NULL,
circular = TRUE,
database = NULL,
methylation = c("auto", "none", "dam_dcm")
)
Arguments
sequence |
DNA text, a named character vector, or a data frame with
|
enzymes |
Optional enzyme names. A data frame is a compatibility
spelling for |
patterns |
Optional custom definitions. |
circular |
Allow recognition and cleavage coordinates to wrap origin. |
database |
Optional parsed pattern database. |
methylation |
Methylation context. |
Value
One row per pattern match without display filtering or deduplication.
Methylation-aware columns include methylation_status, blocked_by,
display_warning, methylation_motif, and sensitivity_source.
enzyme_site_count records the number of distinct cleavage/display
positions for that enzyme on the complete supplied sequence, so it remains
stable after display filtering. For an exactly recognized bundled
reference sequence, the reference_enzyme_profiles attribute records its
saved display set for use by filter_restriction_sites().
See Also
Ready-to-plot flagship inputs
Description
Prepared data for every website flagship. These objects separate source construction from drawing: no file reading, feature discovery, selection, focusing or base extraction is needed on the plotting pages. Original genome source tables remain available in genome_comparison_example.
Format
Four named lists:
- flagship_comparison_example
Entries
chord,collinear,radialandsankey, each containingseq_data, selected links,featuresand orderedlabels. Chord/Radial also contain displayorientation; Collinear/Sankey separateadjacent_linksandcross_links. Collinearroute_controlsapply to the unchanged fixed flagship layout. The additionalcomparisonentry retains the original four-coordinate teaching inputs asseq_data,links,featuresandevents.- flagship_dotplot_example
Complete
seq_dataandlinks, thepair_counts, and readycell_labelsfor all 16 sequence combinations. Label coordinates use the declaredaxis_gapof 4000 bp.- flagship_fusion_example
Selected overview
links,featuresand displayorientation; completeall_features; three labelled relation tables; sourcewindows,focusedlocal tables,detail_features,context_sequencesandcontext_features;base_cds,base_start,base_end, registered-inputbase_cells, andfocus_regions. Source and local coordinates are retained separately.- flagship_circular_example
densecontains the existing dense flagship's sequence, feature, primer and restriction tables.referencescontains 13 complete maps named by original sequence identifier, withseq_data,source_sequence,features,primers,sites,all_site_count,policyand the separate legacygallery_sites.summaryrecords sequence lengths and feature counts.
Details
Nucleotide coordinates are one-based inclusive and measured in bp; pident is a percentage. Biological strands and descending reverse-HSP endpoints are unchanged. Display orientation, route controls and cell-label positions are explicit presets, not biological observations. Rebuild the applicable presets when changing sequence order, gap or alignment geometry.
No compiled plot, grob, device measurement or final label placement is stored. Drawing still performs physical-size geometry and label layout. Complete source records and the actual selected display rows are kept separately.
Source
data-raw/generate_flagship_data.R, after
data-raw/generate_website_data.R. Input fingerprints are recorded in
data-raw/flagship-data-sources.tsv and data-raw/website-data-sources.tsv.
Original FASTA/GFF3/BLAST files and reference plasmid records are unchanged.
Examples
data(flagship_comparison_example)
names(flagship_comparison_example$chord)
Focus ggchord data on one or more loci
Description
Crops sequence, gene and ribbon tables together and relocates retained
coordinates to start at one in each output locus. Multiple loci from the
same source sequence are supported; provide a unique locus_id column to
control their output sequence IDs.
Segmented annotations, cleavage positions and cached feature runs are
cropped and relocated together. Source intervals, source origins and
genomic left/right truncation flags are retained on the returned tables.
An optional sequence column must contain non-missing strings matching
each input length. It is cropped with integer locus boundaries, preserving
character order and case; focusing does not reverse-complement strings.
Alignment cropping is a linear display projection, not a new alignment:
identity is retained, and a scaled alignment length is marked as estimated.
Usage
focus_ggchord_data(
seq_data,
ribbon_data = NULL,
gene_data = NULL,
loci,
expand = 0,
boundary = c("trim", "drop"),
feature_data = NULL
)
Arguments
seq_data |
Sequence table containing |
ribbon_data |
Optional ggchord alignment table. |
gene_data |
Optional gene or feature table. |
loci |
Data frame containing |
expand |
Non-negative number of bases added on both sides, scalar or one value per locus. |
boundary |
Boundary policy. |
feature_data |
Unified annotation input; mutually exclusive with gene_data. |
Value
A list of focused seq_data, ribbon_data, gene_data, normalized
loci, and a compact report including retained/dropped source rows and
truncated output rows. .source_origin is the original genomic position
corresponding to local position one, including after repeated focusing.
See Also
Focus quantitative intervals or samples without bridging omitted windows
Description
Applies the same explicit loci and output IDs as focus_ggchord_data() and
segment_ggchord_data(). It never averages, interpolates, rescales values,
or creates boundary samples. Missing values remain missing. Subsequent
track layers group by the returned window accession, so separate windows
cannot be joined by a line. Source coordinates and original row lineage
survive repeated focusing.
Usage
focus_ggchord_track(
data,
seq_data,
loci,
type = c("point", "interval"),
boundary = c("trim", "drop")
)
Arguments
data |
Quantitative input table. Metadata and mapped values are retained. |
seq_data |
Sequence reference table. |
loci |
Explicit |
type |
|
boundary |
|
Value
An ordinary data frame with focused coordinates. Its
ggchord_track_focus attribute reports output-to-input rows and omitted
input rows; .source_* columns retain earliest source coordinates.
See Also
Examples
library(ggchord)
library(dplyr)
data(plasmid_example_pUC19)
track_seq <- plasmid_example_pUC19 |>
select(accver, length)
starts <- seq.int(1L, track_seq$length, by = 100L)
gc_fraction <- function(sequence) {
bases <- strsplit(sequence, "")[[1]]
mean(bases %in% c("G", "C"))
}
bins <- tibble(
accver = track_seq$accver,
start = starts,
end = pmin(starts + 99L, track_seq$length)
) |>
rowwise() |>
mutate(gc = gc_fraction(substr(plasmid_example_pUC19$sequence, start, end))) |>
ungroup()
loci <- tibble(accver = track_seq$accver, start = 501, end = 2000)
focus_ggchord_track(bins, track_seq, loci, type = "interval")
Add a genomic panel to a Fusion
Description
Add a genomic panel to a Fusion
Usage
fusion_panel(
plot,
id,
side = c("right", "top", "left", "bottom"),
size = NULL,
box = NULL,
angle = NULL,
distance = NULL
)
Arguments
plot |
An independent ggchord genomic plot, another Fusion, or a Cartesian
detail from |
id |
Unique nonempty panel name; |
side |
One of right, top, left, bottom, topright, topleft, bottomright or bottomleft (one panel per named side), or auto for a bounded clockwise perimeter layout with any number of distinct panels that fit the canvas. Auto preserves explicit sizes and all fixed allocations; unlocked default containers may adapt with a 15 mm floor. Placement does not rescale fonts or rotate the child Coord. If no placement is feasible, the build fails explicitly. |
size |
Optional fractional width and height. Out-of-frame allocations fail; overlap fails unless explicitly allowed by the composition. |
box |
Optional explicit rectangle (xmin, xmax, ymin, ymax), optionally named in any order. Numeric values are fractions of the content area after native outer plot decorations and Guides; absolute grid units retain their physical size within that same frame. Use instead of side/size/angle/distance. Out-of-frame boxes fail at build. |
angle |
Optional finite placement angle in degrees counterclockwise from the right, instead of side. Does not rotate the plot or its labels. |
distance |
Positive radial distance from the centre allocation, as a fraction of half the shorter physical allocation dimension; default .8. Angles describe physical canvas directions even on rectangular devices. The allocation must fit without implicit clamping. |
Value
A component for ggchord_fusion().
Examples
data(seq_data_example)
p <- ggchord(seq_data_example) + geom_seq()
ggchord_fusion(p) + fusion_panel(p + coord_collinear(), "right")
quiet <- p + theme(legend.position = "none")
ggchord_fusion(quiet) +
fusion_panel(quiet + coord_sankey(), "mirror", angle = 31, distance = .8)
ggchord_fusion(quiet, center_box = c(.02, .35, .2, .8), allow_overlap = TRUE) +
fusion_panel(quiet + coord_collinear(), "inset", box = c(.25, .98, .3, .7))
Connect real intervals across Fusion panels
Description
Uses ordinary qaccver/saccver and qstart/qend/sstart/send columns. Optional
qpanel/spanel and q_instance/s_instance select exact panels and display
instances. Missing selectors are inferred only when a unique candidate
exists. Query/subject roles never depend on the placement of a panel.
Intervals are one-based inclusive, with ordered fronts spanning [min-1,max];
a one-position interval has nonzero width. Fully visible intervals are
required; split/focus the source data explicitly before composition.
Usage
fusion_ribbon(
data,
mapping = NULL,
qpanel = NULL,
spanel = NULL,
gradient = FALSE,
tip = c("none", "subject"),
allow_repeated = FALSE,
curvature = 0.3,
fill = NULL,
colour = NA,
alpha = 0.35,
linewidth = 0.25,
linetype = 1,
show.legend = NA,
route = c("direct", "avoid", "bundle"),
route_width = 0.8
)
Arguments
data |
A relationship data frame, preserving original endpoints. |
mapping |
Standard ggplot2 aesthetic mapping: fill, colour, alpha, linewidth and linetype. With pident and no explicit fill, Identity is mapped by default with 0/50/80/90/95/100 breaks. Composition uses ordinary scale_fill_* etc.; panel role scales remain local to each panel. |
qpanel, spanel |
Optional fixed panel IDs. Do not also supply their columns. |
gradient |
Opt in to query-to-subject sequence-colour interpolation. Cannot be combined with an explicit fill or fill mapping. |
tip |
|
allow_repeated |
Explicitly allow repeated source_hsp_id display. |
curvature |
Control distance relative to endpoint separation, in |
fill, colour, alpha, linewidth, linetype |
Fixed styles; explicit values take priority over mappings. The default fill without pident is steelblue. |
show.legend |
Standard ggplot2 legend selection: NA follows mappings; TRUE/FALSE or a named logical vector controls guide participation. |
route |
Default direct Bezier ribbons, or avoid for a measured obstacle route. Bundle requires an explicit route_group character column and shares a corridor for each group and ordered panel pair within the layer; every observation, source row, complete front and style remains independent. It does not aggregate evidence or imply biological flow. Avoid preserves complete interval fronts and uses a narrow polygonal corridor between them. Failure to find a clear route is explicit. |
route_width |
Positive corridor width in mm for avoid/bundle (default .8). This is drawing width, not an alignment length or statistical weight. |
Value
A component for ggchord_fusion().
Examples
data(seq_data_example)
data(ribbon_data_example)
p <- ggchord(seq_data_example) + geom_seq()
ggchord_fusion(p) +
fusion_panel(p + coord_collinear(), "detail") +
fusion_ribbon(ribbon_data_example, qpanel = "center", spanel = "detail")
Example gene annotation data
Description
A compact plotting fixture generated deterministically from
examples/gene_track.tsv. Eight features of varied visible lengths are
distributed across each sequence and favour informative annotations.
Because the source records are
strongly strand-biased, the demonstration strand alternates between
"+" and "-"; the biological source value remains available as
source_strand.
Usage
gene_data_example
Format
A data frame containing the following columns:
accver: Sequence accession/version or an unchanged custom identifier
start: Gene start position
end: Gene end position
strand: Strand direction (+/-)
anno: Gene annotation category
source_strand: Strand direction in the source annotation file
Complete genome comparison inputs and flagship display subsets
Description
Unchanged sequence, GFF3 and BLAST records for four genomes, together with
the explicit subsets used by the website flagships. Rebuild with
data-raw/generate_website_data.R; source checksums are recorded in
data-raw/website-data-sources.tsv. No intervals or strands are invented.
Full source tables remain separate from the display selections.
Usage
genome_comparison_example
Format
A named list: sequences includes complete DNA strings; seq_data
contains accession and length; annotations, alignments and
source_alignments retain complete imported records (the latter adds
source-file and HSP identifiers). genes contains all CDS. links,
features, chord_features, linear_features, adjacent_links and
cross_links are the existing deterministic display selections, in their
original order. Coordinates are one-based inclusive, lengths are in bp,
and pident is a percentage. Displayed negative subject endpoints may be
descending. Import provenance is retained on the imported tables.
Source
Repository examples/fasta/, examples/gff3/ and
examples/blastn-standard/; their source documentation accompanies the
original files. The generator records the exact filtering rules.
Examples
data(genome_comparison_example)
head(genome_comparison_example$seq_data)
Draw HSP alignment segments
Description
Projects each standard ribbon-data row from (qstart, sstart) to
(qend, send) in coord_dotplot(). All four endpoints are retained;
reverse alignments must have normalized descending endpoints, as returned
by read_paf(). Explicit unknown direction or strand values are omitted
with a warning and recorded in the layout connection report.
This is an HSP-level view, not a reconstruction of mismatches or gaps.
Usage
geom_alignment_segment(
mapping = NULL,
data = NULL,
colour = "#59636D",
alpha = 0.6,
linewidth = 0.4,
linetype = 1,
position = "identity",
show.legend = NA,
inherit.aes = FALSE,
allow_repeated = FALSE,
...
)
Arguments
mapping, data |
Standard ggplot2 mapping and layer data. Data defaults
to the constructor's |
colour, alpha, linewidth, linetype |
Fixed styles. Mapped styles use
|
position |
Only |
show.legend, inherit.aes |
Standard ggplot2 layer arguments. |
allow_repeated |
Allow explicitly identified |
... |
Additional arguments passed to ggplot2's segment geometry. |
Value
A ggplot2 layer for a ggchord Dotplot.
Examples
data(seq_data_example)
data(ribbon_data_example)
ggchord(seq_data_example, ribbon_data_example) +
geom_alignment_segment(aes(link_colour = pident)) +
coord_dotplot()
Draw generic genomic features
Description
A general layer for CDS, tRNA, rRNA, repeat, CRISPR, promoter or user-defined features. It supports directional arrows, blocks, notched chevrons and lollipops, all generated against the sequence's real local curve. Feature fill and geometry use independent role-specific scales.
Usage
geom_feature(
mapping = NULL,
data = NULL,
shape = "arrow",
width = NULL,
arrow_head_length = 0.04,
arrow_head_width = 1,
arrow_head_style = c("shouldered", "flush", "triangle"),
short_feature = c("auto", "wedge", "block"),
segment_boundaries = TRUE,
boundary_colour = "#666666",
boundary_linewidth = 0.25,
boundary_linetype = "22",
position = "identity",
show.legend = TRUE,
inherit.aes = FALSE,
...
)
Arguments
mapping |
Optional aesthetic mapping. Role aesthetics such as
|
data |
data.frame with |
shape |
Fixed feature geometry. An explicitly supplied shape takes
precedence over |
width |
Optional numeric/vector/list controlling width in the shared feature geometry engine. In a circular feature-label composition, the base width responds to final label size within bounded limits. |
arrow_head_length, arrow_head_width |
Arrow-head dimensions in the
sequence-local frame, shared with |
arrow_head_style |
Arrowhead construction: |
short_feature |
Fallback for arrows too short to hold their requested head: an automatically compressed directional glyph, a wedge, or a block. |
segment_boundaries |
Draw explicit internal marks carried by a
segmented feature. Contiguous source-segment joins use dotted dividers;
a non-solid segment-level |
boundary_colour, boundary_linewidth, boundary_linetype |
Appearance of internal segment joins. |
position |
Feature placement. Use |
show.legend, inherit.aes |
Standard ggplot2 layer arguments. |
... |
Additional fixed polygon aesthetics. |
Value
A ggplot2 layer.
Examples
library(dplyr)
data(plasmid_example_pUC19)
seqs <- plasmid_example_pUC19 |>
select(accver, length)
# Restrict discovery to two named features on the real plasmid.
feature_source <- find_common_features(
plasmid_example_pUC19, features = c("AmpR", "ori"), mode = "dna"
)
features <- feature_source |>
select(accver, start, end, strand, type, anno)
# ASCII display copy for the default PDF help-example device.
features <- features |>
mutate(anno = gsub("\u03b1", "alpha", anno, fixed = TRUE))
ggchord(seq_data = seqs) +
geom_seq() +
geom_feature(
data = features,
shape = "block"
) +
coord_circular()
Label generic genomic features
Description
Label generic genomic features
Usage
geom_feature_label(
mapping = NULL,
data = NULL,
label_orientation = c("feature", "horizontal", "radial", "tangent"),
label_side = c("outside", "inside", "auto"),
label_overlap = c("hide", "nudge", "allow"),
label_wrap = NULL,
label_rotation = NULL,
label_radial_offset = 0.04,
label_circum_offset = NULL,
label_circum_limit = NULL,
position = "identity",
show.legend = FALSE,
inherit.aes = FALSE,
...
)
Arguments
mapping, data |
Standard layer inputs. Map feature text with |
label_orientation |
One of |
label_side |
One of |
label_overlap |
Fixed-label collision policy. |
label_wrap |
Optional character wrapping width. |
label_rotation |
Optional numeric/vector/list. Label rotation angle, default 0 |
label_radial_offset |
Optional numeric/vector/list. Radial offset of labels, default 0.04 |
label_circum_offset |
Optional numeric/vector/list. Circumferential offset of labels, default 0 |
label_circum_limit |
Optional logical/vector/list. Whether to limit circumferential offset, default TRUE |
position |
Feature Position used for the label anchor.
In |
show.legend, inherit.aes |
Standard ggplot2 layer arguments. |
... |
Additional text parameters. |
Value
A ggplot2 layer.
Automatically arrange generic feature labels
Description
Automatically arrange generic feature labels
Usage
geom_feature_label_repel(
mapping = NULL,
data = NULL,
label_layout = c("feature", "radial", "auto", "callout"),
label_wrap = NULL,
label_fit = c("wrap", "none", "ellipsis", "auto", "shrink"),
label_max_lines = 2L,
label_side = c("outside", "inside", "auto"),
max_overlaps = Inf,
external = TRUE,
position = "identity",
show.legend = FALSE,
inherit.aes = FALSE,
label_min_size = 1.5,
label_segment_overlap = "fade",
label_segment_overlap_alpha = 0.18,
label_segment_linetype = "auto",
label_segment_layer = c("below", "above"),
label_repeat = c("individual", "bracket"),
label_segment_colour = "auto",
...
)
Arguments
mapping, data |
Standard layer inputs. Map feature text with |
label_layout |
One of |
label_wrap, label_fit, label_max_lines |
Text fitting controls.
|
label_side |
One of |
max_overlaps |
Maximum unresolved overlaps. |
external |
Whether the staged feature layout may place a label outside
the circular backbone after inside and adjacent placement fail. When
|
position |
Feature Position used for the label anchor.
In |
show.legend, inherit.aes |
Standard ggplot2 layer arguments. |
label_min_size |
Minimum text size in millimetres for explicit shrink, default 1.5. Must not exceed the requested text size. Original text, requested/final sizes and fitting reason are exported with the label. |
label_segment_overlap |
Character, default |
label_segment_overlap_alpha |
Numeric in |
label_segment_linetype |
Character or numeric, default "auto".
Leader-line linetype. |
label_segment_layer |
Draw leaders |
label_repeat |
|
label_segment_colour |
|
... |
Additional text parameters. |
Details
Manual label rotation, offsets, orientation and overlap policy belong to
geom_feature_label(). Their label_* controls are rejected by automatic
layers rather than silently ignored.
Value
A composite text and leader-line layer.
Examples
library(dplyr)
data(plasmid_example_pUC19)
seqs <- plasmid_example_pUC19 |>
select(accver, length)
# Restrict discovery to two named features on the real plasmid.
feature_source <- find_common_features(
plasmid_example_pUC19, features = c("AmpR", "ori"), mode = "dna"
)
features <- feature_source |>
slice_head(n = 4) |>
select(accver, start, end, strand, type, anno)
# ASCII display copy for the default PDF help-example device.
features <- features |>
mutate(anno = gsub("\u03b1", "alpha", anno, fixed = TRUE))
ggchord(seq_data = seqs) +
geom_seq() +
geom_feature(data = features, position = position_plasmid()) +
geom_feature_label_repel(data = features, position = position_plasmid(),
label_segment_layer = "below", label_segment_colour = "grey50") +
coord_circular()
# A shared display label preserves all seven biological operator records.
repeated <- find_common_features(plasmid_example_pTRE_Tight_BI)
feature_position <- position_feature_stack(base_position = position_plasmid())
ggchord(plasmid_example_pTRE_Tight_BI[c("accver", "length")],
feature_data = repeated) +
geom_seq(seq_style = "double") +
geom_feature_plasmid(position = feature_position) +
geom_feature_label_repel(position = feature_position,
label_repeat = "bracket", label_fit = "shrink", label_min_size = 2.5) +
coord_circular() +
theme_ggchord_plasmid()
Draw annotated features on a circular plasmid
Description
A concise plasmid-map preset built on geom_feature(). It uses the same
generic feature engine, while selecting a compact circular track,
protruding shouldered block arrows, and dashed internal segment joins.
Usage
geom_feature_plasmid(
mapping = NULL,
data = NULL,
shape = "arrow",
width = 0.058,
arrow_head_length = 0.068,
arrow_head_width = 1.42,
arrow_head_style = "shouldered",
short_feature = "auto",
segment_boundaries = TRUE,
boundary_colour = "#666666",
boundary_linewidth = 0.25,
boundary_linetype = "22",
position = NULL,
show.legend = FALSE,
inherit.aes = FALSE,
...
)
Arguments
mapping |
Optional aesthetic mapping. Role aesthetics such as
|
data |
data.frame with |
shape |
Fixed feature geometry. An explicitly supplied shape takes
precedence over |
width |
Track width; the default matches the compact feature bands used by desktop plasmid editors. |
arrow_head_length, arrow_head_width |
Arrow-head dimensions in the
sequence-local frame, shared with |
arrow_head_style |
Arrowhead construction: |
short_feature |
Fallback for arrows too short to hold their requested head: an automatically compressed directional glyph, a wedge, or a block. |
segment_boundaries |
Draw explicit internal marks carried by a
segmented feature. Contiguous source-segment joins use dotted dividers;
a non-solid segment-level |
boundary_colour, boundary_linewidth, boundary_linetype |
Appearance of internal segment joins. |
position |
Feature position. |
show.legend, inherit.aes |
Standard ggplot2 layer arguments. |
... |
Additional fixed polygon aesthetics. |
Value
A ggplot2 layer.
Add a gene arrow layer
Description
A directed-gene shortcut using the generic geom_feature()
constructor with arrow geometry and the independent gene_fill role.
Gene input still requires a known + or - strand; use
geom_feature() for unknown strands.
The gene fill scale is kept independent from the ribbon's fill scale via a
separate internal aesthetic used by the ribbon layer.
Usage
geom_gene(
mapping = NULL,
data = NULL,
width = NULL,
arrow_head_length = 0.04,
arrow_head_width = 1,
arrow_head_style = c("shouldered", "flush", "triangle"),
short_feature = c("auto", "wedge", "block"),
position = "identity",
show.legend = TRUE,
inherit.aes = FALSE,
...
)
Arguments
mapping |
Default NULL (uses pre-computed data) |
data |
Optional layer table or function, overriding constructor data.
With unified |
width |
Optional numeric/vector/list. Width of gene arrows, default 0.05 |
arrow_head_length, arrow_head_width |
Shared arrow-head dimensions in the sequence-local frame. |
arrow_head_style |
Arrowhead construction: shouldered, flush, or a full triangular wedge. |
short_feature |
Fallback for arrows too short to hold their requested head: automatic wedge/block selection, a wedge, or a block. |
position |
Feature placement. Use |
show.legend, inherit.aes |
Standard ggplot2 layer arguments. |
... |
Additional arguments passed to |
Value
A ggplot2 layer. To annotate the genes with their labels,
add a geom_gene_label() layer.
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
data(gene_data_example)
genes <- gene_data_example |>
transmute(accver, start, end, strand = source_strand)
ggchord(seq_data = seqs, gene_data = genes) +
geom_seq() +
geom_gene()
Add a gene label layer
Description
Draws the gene annotation labels on a chord diagram. This layer is
independent from geom_gene(): add it after geom_gene()
to annotate the gene arrows with their texts.
Usage
geom_gene_label(
mapping = NULL,
data = NULL,
label_orientation = "horizontal",
label_side = "outside",
label_overlap = "hide",
label_rotation = NULL,
label_radial_offset = 0.04,
label_circum_offset = NULL,
label_circum_limit = NULL,
label_wrap = NULL,
position = "identity",
show.legend = FALSE,
inherit.aes = FALSE,
...
)
Arguments
mapping |
Default NULL (uses pre-computed data) |
data |
Optional layer table or function. Default data follows the
gene/CDS selection described in |
label_orientation |
Character, default |
label_side |
Character, default |
label_overlap |
Character, default |
label_rotation |
Optional numeric/vector/list. Label rotation angle, default 0 |
label_radial_offset |
Optional numeric/vector/list. Radial offset of labels, default 0.04 |
label_circum_offset |
Optional numeric/vector/list. Circumferential offset of labels, default 0 |
label_circum_limit |
Optional logical/vector/list. Whether to limit circumferential offset, default TRUE |
label_wrap |
Numeric or NULL, default NULL. When set, long gene annotations are wrapped at this many characters (e.g. 15), which makes the labels narrower and less prone to overlap. |
position |
Position adjustment. Supply the same
|
show.legend, inherit.aes |
Standard ggplot2 layer arguments. |
... |
Additional arguments passed to |
Details
This is the deterministic, fixed-position label layer. By default labels
sit outside their sequence and labels that would collide are omitted in
input-row order. Use label_overlap = "nudge" to retain the
small position adjustment, or "allow" to draw every label at its
requested position. For automatic arrangement with leader lines, use
geom_gene_label_repel() instead.
Value
A ggplot2 layer. To let the labels avoid each other and the
genes (with leader lines), use geom_gene_label_repel()
instead.
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
data(gene_data_example)
genes <- gene_data_example |>
slice_head(n = 3) |>
transmute(accver, start, end, strand = source_strand, anno)
ggchord(seq_data = seqs, gene_data = genes) +
geom_seq() +
geom_gene() +
geom_gene_label()
Add an automatically arranged gene label layer
Description
Like geom_gene_label(), with deterministic external label
placement. The default "radial" keeps horizontal text on a contour
following each sequence; crowded names fan out along that contour.
"auto" aligns left/right names in columns and uses radial placement
elsewhere. "arc" rotates text along the sequence tangent.
Usage
geom_gene_label_repel(
mapping = NULL,
data = NULL,
label_layout = "radial",
label_wrap = NULL,
label_fit = "wrap",
label_max_lines = 2L,
label_side = "outside",
max_overlaps = Inf,
label_segment_overlap = "fade",
label_segment_overlap_alpha = 0.18,
label_segment_linetype = "auto",
position = "identity",
show.legend = FALSE,
inherit.aes = FALSE,
label_min_size = 1.5,
...
)
Arguments
mapping |
Default NULL (uses pre-computed data) |
data |
Optional layer table or function. Default data follows the
gene/CDS selection described in |
label_layout |
Character, default |
label_wrap |
Numeric or NULL, default NULL. When set, long gene
annotations are wrapped at this many characters (e.g. 15), overriding
|
label_fit |
Character, default |
label_max_lines |
Positive integer, default 2. Maximum number of
lines used by adaptive |
label_side |
Character, default "outside". Which side of the arc
the labels sit on. |
max_overlaps |
Numeric, default Inf. Hide labels that still overlap more than this many other labels after repulsion (ggrepel-style decluttering). Use a finite value to clean up crowded plots. |
label_segment_overlap |
Character, default |
label_segment_overlap_alpha |
Numeric in |
label_segment_linetype |
Character or numeric, default "auto".
Leader-line linetype. |
position |
Position adjustment. Supply the same
|
show.legend, inherit.aes |
Standard ggplot2 layer arguments. |
label_min_size |
Minimum text size in millimetres for explicit
|
... |
Additional text styles and drawing options. Automatic layouts
own rotation, offsets, orientation and overlap policy; use
|
Details
Low-level force, padding, orientation and segment arguments used by earlier
releases have been removed and now produce an error. Use
label_layout for automatic placement, or
geom_gene_label() for manual rotation and offsets.
Value
A ggplot2 layer that draws labels and leader lines together.
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
data(gene_data_example)
genes <- gene_data_example |>
group_by(accver) |>
slice_head(n = 2) |>
ungroup() |>
transmute(accver, start, end, strand = source_strand, anno)
ggchord(seq_data = seqs, gene_data = genes) +
geom_seq() +
geom_gene() +
geom_gene_label_repel(label_wrap = 20)
Draw point-to-point sequence links
Description
Requires qaccver, saccver, qpos and spos. Positions use the same genomic
coordinates as sequence tracks. Curves run from query to subject; an arrow
supplied by arrow() therefore points to the subject by default.
Usage
geom_link_line(
mapping = NULL,
data = NULL,
link_type = c("curve", "straight"),
link_gap = NULL,
link_ctrl_point = NULL,
link_avoid = c("none", "smooth", "uniform"),
link_branch = c("none", "query", "subject"),
link_branch_fraction = 0.15,
arrow = NULL,
colour = "#59636D",
alpha = 0.6,
linewidth = 0.4,
linetype = 1,
position = "identity",
show.legend = NA,
inherit.aes = FALSE,
between = NULL,
allow_repeated = FALSE,
...
)
Arguments
mapping, data |
Standard ggplot2 mapping and layer data, including data functions. |
link_type |
Either "curve" (default) or "straight". |
link_gap |
Explicit endpoint spacing. With the default
|
link_ctrl_point |
Bezier control points: two numbers, four numbers, or a list per input row. |
link_avoid |
One of "none" (default), "smooth", or "uniform". Explicit gap takes precedence. |
link_branch |
Share equal query or subject endpoints: "none", "query", "subject". |
link_branch_fraction |
Shared length relative to the shortest member, in (0, 0.5]. |
arrow |
A grid arrow specification, or NULL. |
colour, alpha, linewidth, linetype |
Fixed styles; mappings use link_* aesthetics.
An explicitly supplied fixed value takes precedence over the matching
mapping. Omit the fixed argument to retain a mapped style, including an
inherited mapping when |
position, show.legend, inherit.aes |
Standard ggplot2 layer arguments. |
between |
Two display-instance names or declared-order indices. |
allow_repeated |
Allow repeated display of an explicitly declared source_hsp_id. |
... |
Additional path parameters. |
Value
A ggplot2 layer.
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
data(ribbon_data_example)
links <- ribbon_data_example |>
select(qaccver, saccver, qstart, qend, sstart, send, pident, length)
points <- links |>
transmute(qaccver, saccver,
qpos = floor((qstart + qend) / 2),
spos = floor((sstart + send) / 2)
)
ggchord(seq_data = seqs) +
geom_seq() +
geom_link_line(data = points)
Add an alignment ribbon layer
Description
Draws alignment ribbons with Identity fills by default.
Set gradient = TRUE for query-to-subject sequence-colour interpolation. Explicit fill, ribbon_fill mappings or ribbon fill scales
replace the gradient; map ribbon_fill = pident for an Identity guide. Alignment length and identity are never inferred from endpoints.
Alternative mappings and legends are controlled with aes(), scale_*()
and guides(). With gradient enabled, shared trunks keep the common
endpoint colour and branches interpolate between their endpoint colours. Optional tips appear
only at real subject fronts.
Usage
geom_link_ribbon(
mapping = NULL,
data = NULL,
link_ctrl_point = NULL,
link_gap = NULL,
link_avoid = c("uniform", "none", "smooth"),
link_branch = c("none", "query", "subject"),
link_branch_fraction = 0.15,
fill = NULL,
alpha = 0.42,
colour = "#59636D",
linewidth = 0.08,
linetype = NULL,
adjacent_only = NULL,
pairs = NULL,
position = "identity",
show.legend = TRUE,
inherit.aes = FALSE,
nonadjacent_linewidth = 0.4,
between = NULL,
allow_repeated = FALSE,
tip = c("none", "subject"),
gradient = FALSE,
...
)
Arguments
mapping |
Default NULL (uses pre-computed data) |
data |
Default NULL (retrieved automatically from the layout) |
link_ctrl_point |
Optional vector/list of Bezier edge controls.
Two numbers specify one shared control; four numbers specify controls for
the two ribbon edges. A per-row list may contain pairs of coordinate vectors.
NULL uses the origin |
link_gap |
Optional numeric/vector controlling spacing between
sequences and ribbon endpoints. With the default
|
link_avoid |
One of |
link_branch |
Share equal query or subject endpoints: "none", "query", "subject". |
link_branch_fraction |
Shared length relative to the shortest member, in (0, 0.5]. |
fill |
Optional fixed ribbon fill. NULL uses the default Identity fill. |
alpha, colour, linewidth |
Standard fixed ribbon styles. Explicit values
take precedence over matching mappings; omitted defaults do not suppress
user mappings. For example, omit |
linetype |
Fixed outline line type. The default |
adjacent_only |
Whether only neighbouring sequences are connected.
|
pairs |
Optional data frame with |
position, show.legend, inherit.aes |
Standard ggplot2 layer arguments. |
nonadjacent_linewidth |
Fixed outline width for non-adjacent displayed
rows in |
between |
Two display-instance names or declared-order indices for a unique route. |
allow_repeated |
Explicitly allow a declared source_hsp_id in more than one displayed relation. |
tip |
Full interval fronts (none, default), or an optional subject taper. The shoulder retains the translated target endpoint span at 88 percent of the channel. The tip is a decorative front-midpoint marker, not a single matched base or biological transfer direction. Degenerate fronts fall back to the full front with a warning. Source intervals are unchanged. |
gradient |
Logical. Opt into endpoint sequence-colour interpolation; default FALSE. Explicit fill, mapping and scales still take priority. |
... |
Additional arguments passed to |
Value
A ggplot2 layer.
Examples
library(dplyr)
links <- ribbon_data_example |>
slice_head(n = 1) |>
select(qaccver, saccver, qstart, qend, sstart, send)
seqs <- seq_data_example |>
filter(accver %in% c(links$qaccver, links$saccver)) |>
select(accver, length)
ggchord(seq_data = seqs, ribbon_data = links) +
geom_seq() +
geom_link_ribbon()
Draw primer binding ranges on a circular sequence
Description
Primers are slender directional arcs drawn between the two lines of a
double sequence backbone by default, not arrows in the feature stack. Add
geom_primer_label_repel() for the matching unboxed label and leader.
Usage
geom_primer(
mapping = NULL,
data = NULL,
side = c("between", "outside", "inside"),
arc_offset = 0.045,
arc_linewidth = 0.026,
colour = "#A020F0",
position = NULL,
show.legend = FALSE,
inherit.aes = FALSE,
...
)
Arguments
mapping, data |
Standard layer inputs. |
side |
Backbone lane used by the primer arc. |
arc_offset |
Distance from the backbone centre when |
arc_linewidth |
Radial width of the primer arc. |
colour |
Primer arc colour. |
position, show.legend, inherit.aes |
Standard layer arguments. |
... |
Additional parameters passed to |
Value
A ggplot2 layer.
Examples
library(dplyr)
data(plasmid_example_pUC19)
seqs <- plasmid_example_pUC19 |>
select(accver, length)
primers <- find_primer_bindings(plasmid_example_pUC19, set = "reference") |>
slice_head(n = 2)
ggchord(seq_data = seqs) +
geom_seq() +
geom_primer(data = primers) +
geom_primer_label_repel(data = primers) +
coord_circular()
Arrange primer labels and leaders
Description
Primer labels are unboxed, use the primer colour, and show one-based inclusive binding coordinates by default. Their leaders start at the directional primer arc's arrow tip (the primer 3-prime end). Factor start/end columns use their numeric labels for both displayed text and retained binding-coordinate metadata, matching feature geometry.
Usage
geom_primer_label_repel(
mapping = NULL,
data = NULL,
side = c("outside", "inside"),
show_location = TRUE,
colour = "#A020F0",
max_overlaps = Inf,
position = NULL,
show.legend = FALSE,
inherit.aes = FALSE,
...
)
Arguments
mapping, data |
Standard layer inputs. |
side |
Side of the backbone on which the primer callout is arranged.
|
show_location |
Include the binding range in the label. |
colour |
Primer arc colour. |
max_overlaps |
Maximum unresolved overlaps. |
position, show.legend, inherit.aes |
Standard layer arguments. |
... |
Additional parameters passed to |
Value
A composite text and leader-line layer.
Draw physically readable residue cells
Description
A standard Cartesian ggplot layer for local nucleotide/protein excerpts.
Map x to alignment columns (or independently known source positions), y
to sequence rows and label to actual characters. It does not compute an
alignment or project through ggchord's biological backbone coordinates.
Use register_ggchord_alignment() to associate exact source positions with
a Fusion/magnify detail panel. Half-cell extents train position scales so
first/last cells remain fully visible by default.
Native scales must be identity or reverse; nonlinear scales and non-Cartesian
coordinates are rejected rather than misrepresenting single-position cells.
Usage
geom_residue(
mapping = NULL,
data = NULL,
overflow = c("tile", "error"),
position = "identity",
show.legend = FALSE,
inherit.aes = TRUE,
line_width = NULL,
...
)
Arguments
mapping, data |
Standard ggplot2 layer mapping and data. Required
aesthetics are x, y and label. Ordinary colour, fill, alpha, size, family
and fontface mappings/scales are supported. Explicit |
overflow |
|
position, show.legend, inherit.aes |
Standard ggplot2 layer arguments. |
line_width |
Optional positive integer number of columns per displayed line. NULL (default) keeps one line. Lines start at the smallest displayed x value; gaps occupy columns. Multiple sequences share the same breaks. Row labels show the original column range; the x axis counts within a line. Wrapping changes display only, preserving original input/source coordinates. Registered Fusion selections must fit one displayed line; split a selection crossing lines into explicit source intervals. |
... |
Fixed text/cell aesthetics and na.rm, passed to the layer. |
Details
At drawing time, each cell's final physical width/height is compared with
its actual glyph metrics. overflow = "tile" omits letters that cannot fit
and retains their mapped fill cells; "error" requires readable letters.
Explicit font sizes are never silently reduced. The decision is remade at every target
size, including standard ggsave; DPI alone does not supply physical space.
Cells meet at their edges to form a continuous alignment matrix. When the
plot still uses its default Cartesian coordinate system, the layer supplies
a fixed 1:1 aspect ratio so rows remain as compact as alignment columns.
Explicit coordinates take priority. Without a size mapping or fixed size,
characters grow uniformly to fit their cells, with a 3 mm readability floor;
smaller cells use the same overflow policy rather than shrinking the text.
When fill is not supplied, label is mapped to fill. A chemistry scale is
inferred from the data's explicit alphabet column (DNA/RNA/AA; otherwise AA).
Existing user fill mappings, fixed fills and scales take priority.
See scale_fill_residue() for explicit alphabet and palette control.
Value
A standard ggplot2 layer. Cells span one x unit and one y unit. Use discrete y rows or unit-spaced rows.
See Also
read_aligned_fasta(), map_alignment_position()
Examples
# Explicit synthetic format example; real-data workflow is in the tutorial.
cells <- as_ggchord_alignment(c(A = "AC-G", B = "ACTG"), "DNA")
ggplot2::ggplot(cells, aes(alignment_column, accver, label = symbol)) +
geom_residue(aes(fill = symbol))
long <- as_ggchord_alignment(c(A = strrep("ACGT", 25)), "DNA")
ggplot2::ggplot(long, aes(alignment_column, accver, label = symbol)) +
geom_residue(line_width = 50)
Draw restriction sites, labels and deterministic leaders
Description
Draw restriction sites, labels and deterministic leaders
Usage
geom_restriction_site(
mapping = NULL,
data = NULL,
label = TRUE,
label_style = c("enzyme_position", "enzyme", "position"),
label_order = c("auto", "enzyme_position", "position_enzyme"),
label_side = c("outside", "inside", "auto"),
leader = c("radial", "elbow", "straight"),
min_label_gap = NULL,
tick_length = 0.04,
label_offset = 0.18,
colour = "#202020",
linewidth = 0.28,
label_size = 3.2,
fontface = NULL,
family = NULL,
position = "identity",
show.legend = FALSE,
inherit.aes = FALSE,
...
)
Arguments
mapping, data |
Standard layer inputs. |
label |
Draw labels. |
label_style |
Label enzyme and position, enzyme only, or position only. |
label_order |
Automatic mirrored label order, enzyme first, or position first. |
label_side |
Draw labels outside, inside, or automatically. |
leader |
Leader routing style. The default |
min_label_gap |
Minimum genomic fraction between label slots. |
tick_length, label_offset |
Local-normal distances. |
colour, linewidth, label_size, fontface, family |
Fixed appearance. With
the default |
position, show.legend, inherit.aes |
Standard layer arguments. |
... |
Additional geom parameters. |
Value
A ggplot2 layer.
See Also
Add a sequence arc layer
Description
Draws arcs (or straight lines, depending on the curvature setting) representing sequences in the chord diagram. Sequence layout parameters (order, orientation, radius, curvature, colors, etc.) are specified here.
Usage
geom_seq(
mapping = NULL,
data = NULL,
seq_order = NULL,
seq_orientation = NULL,
seq_gap = NULL,
seq_radius = NULL,
seq_curvature = NULL,
seq_style = c("auto", "single", "double", "band"),
seq_backbone_gap = 0.025,
seq_backbone_width = 0.035,
linewidth = 0.9,
position = "identity",
show.legend = TRUE,
inherit.aes = FALSE,
length_mode = c("proportional", "equal"),
...
)
Arguments
mapping |
Default NULL (uses pre-computed data) |
data |
Default NULL (retrieved automatically from the layout) |
seq_order |
Source IDs in display order. Repeats create display instances; use names such as c(A_high='A', B='B', A_low='A') for stable instance IDs. Repeated-entity HSPs require a unique between route on each link layer. |
seq_orientation |
Optional numeric (1 or -1). Sequence orientation, default 1 |
seq_gap |
Optional numeric. Gap proportion between sequences, default
0.03 in chord coordinates. A named vector can set the gap after each
sequence; omitted IDs use the coordinate default. In |
seq_radius |
Optional numeric (> 0). Sequence arc radius, default 1.0 |
seq_curvature |
Optional numeric. Signed arc bow (0=straight, 1=standard arc, negative=opposite bow), default 1.0. Finite positive and negative values are accepted without clipping; magnitudes above 1 amplify the bow. |
seq_style |
Backbone geometry. |
seq_backbone_gap |
Gap between double backbone lines. |
seq_backbone_width |
Width of a band backbone. |
linewidth |
Arc line width, default 0.9 |
position, show.legend, inherit.aes |
Standard ggplot2 layer arguments. |
length_mode |
|
... |
Additional fixed path aesthetics. |
Value
A ggplot2 layer.
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
ggchord(seq_data = seqs) +
geom_seq()
Mark cropped ends of linear sequences
Description
Adds two short diagonal strokes at each truncated sequence end in
coord_collinear(). Metadata returned by focus_ggchord_data()
determines the truncated genomic ends; reversed sequence orientation moves
each mark to the corresponding displayed end. These marks are decorations
and do not change the source sequence or feature coordinates.
Usage
geom_seq_break(
mapping = NULL,
data = NULL,
break_width = 0.02,
break_height = 0.04,
linewidth = 0.4,
colour = "#3D4348",
position = "identity",
show.legend = FALSE,
inherit.aes = FALSE,
...
)
Arguments
mapping, data |
Standard layer mapping and sequence data. By default,
use the plot's sequence table. Truncation is read from
|
break_width, break_height |
Width and height of the complete break mark in linear layout units. These are layout distances, not millimetres. |
linewidth, colour |
Fixed line appearance. Ordinary visual aesthetics can also be mapped and controlled by their ggplot2 scales. |
position, show.legend, inherit.aes |
Standard ggplot2 layer arguments. |
... |
Additional parameters passed to |
Value
A ggplot2 layer. Other ggchord coordinate systems are unsupported.
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
loci <- tibble(
accver = seqs$accver, start = floor(seqs$length * .25),
end = floor(seqs$length * .75)
)
focused <- focus_ggchord_data(seqs, loci = loci)
ggchord(seq_data = focused$seq_data) +
geom_seq() +
geom_seq_break() +
coord_collinear()
Add a circular-sequence centre label
Description
Add a circular-sequence centre label
Usage
geom_seq_center_label(
mapping = NULL,
data = NULL,
name = TRUE,
length = TRUE,
separator = "\n",
name_style = list(),
length_style = list(),
show.legend = FALSE,
inherit.aes = FALSE,
...
)
Arguments
mapping, data |
Standard layer inputs. |
name |
Show the sequence name. A character value overrides the name. |
length |
Show the formatted sequence length. |
separator |
Separator between name and length. |
name_style, length_style |
Named lists of fixed text-style overrides
for the name and length grobs. Supported fields are |
show.legend, inherit.aes |
Standard ggplot2 layer arguments. |
... |
Additional arguments passed to |
Value
A ggplot2 layer.
Add a sequence label layer
Description
Places sequence labels at the midpoint of each sequence arc, radially offset from the arc. Labels can be styled via their radial offset, rotation, font size, text orientation and justification.
Usage
geom_seq_label(
mapping = NULL,
data = NULL,
seq_label_radius = 1,
seq_label_rotation = NULL,
labels = NULL,
seq_label_orientation = c("arc", "horizontal"),
seq_label_hjust = NULL,
seq_label_vjust = NULL,
check_overlap = FALSE,
position = "identity",
show.legend = FALSE,
inherit.aes = FALSE,
...
)
Arguments
mapping |
Default NULL (uses pre-computed data) |
data |
Default NULL (retrieved automatically from the layout) |
seq_label_radius |
Optional numeric/vector. Radial position of the
labels as a multiplier of the sequence arc radius: |
seq_label_rotation |
Optional numeric/vector. Additional label rotation
(degrees) on top of the arc-aligned orientation, default NULL (0). Ignored
when |
labels |
Optional character vector. Override the label texts
(defaults to the sequence labels from |
seq_label_orientation |
Character, default "arc". Label text
orientation: |
seq_label_hjust |
Optional numeric/vector. Horizontal justification of
the labels, default NULL. The default arc orientation uses -0.2 so the
text sits just inside the sequence; with
|
seq_label_vjust |
Optional numeric/vector. Vertical justification of the labels, default NULL (0.5). |
check_overlap |
Logical, default FALSE. When TRUE, labels that would
overlap a previously drawn label are skipped (ggplot2's
|
position, show.legend, inherit.aes |
Standard ggplot2 layer arguments. |
... |
Additional arguments passed to |
Value
A ggplot2 layer.
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
ggchord(seq_data = seqs) +
geom_seq() +
geom_seq_label()
Highlight regions along sequence arcs
Description
Draws rectangular bands on sequence arcs for one or more coordinate intervals. This is useful for marking loci, repeats, CRISPR arrays, or other user-defined regions without turning them into gene arrows.
Usage
geom_seq_region(
mapping = NULL,
data = NULL,
fill = "#F59E0B",
colour = "#B45309",
alpha = 0.25,
region_width = 0.08,
region_offset = 0,
region_side = c("inside", "outside", "auto"),
position = "identity",
show.legend = FALSE,
inherit.aes = FALSE,
...
)
Arguments
mapping |
Default NULL (uses pre-computed data) |
data |
data.frame with at least |
fill |
Character. Default fill colour for regions, default
|
colour |
Outline colour, default |
alpha |
Numeric (0-1). Region alpha, default 0.25. |
region_width |
Numeric. Band width in chord radius units, default 0.08. |
region_offset |
Numeric. Radial offset from the sequence arc, default 0. |
region_side |
Character. |
position, show.legend, inherit.aes |
Standard ggplot2 layer arguments. |
... |
Additional arguments passed to |
Value
A ggplot2 layer.
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
data(ribbon_data_example)
links <- ribbon_data_example |>
select(qaccver, saccver, qstart, qend, sstart, send)
region <- tibble(
accver = links$qaccver[1], start = min(links$qstart[1], links$qend[1]),
end = max(links$qstart[1], links$qend[1])
)
ggchord(seq_data = seqs) +
geom_seq() +
geom_seq_region(data = region)
Add a shared sequence-position scale bar to a linear display
Description
Adds a free-standing reference bar in the empty space outside the sequence
envelope. Its length uses the same sequence-position-to-x conversion as every backbone in
coord_collinear(), including independent windows on shared display rows.
Display gaps are never interpreted as genomic length. Local reversals and
original-source axis labels do not change the bar's sequence scale. Chord and
circular coordinates have local sequence axes instead and are rejected.
Usage
geom_seq_scale(
mapping = NULL,
data = NULL,
length = NULL,
label = NULL,
location = c("bottomleft", "bottomright", "topleft", "topright"),
offset = grid::unit(c(0, 6), "mm"),
tick_height = grid::unit(1.5, "mm"),
label_gap = grid::unit(1.5, "mm"),
linewidth = 0.4,
colour = "#3D4348",
size = 3,
position = "identity",
show.legend = FALSE,
inherit.aes = FALSE,
...
)
Arguments
mapping, data |
Standard ggplot2 layer inputs. Optional |
length |
Optional fixed positive integer length in the sequence unit. Cannot be
combined with a |
label |
Optional fixed character label, or a function receiving the
chosen lengths. |
location |
Corner of the sequence envelope used for automatic placement. |
offset |
Two non-negative distances, horizontal then vertical. Absolute grid units are supported; plain numeric values are layout-unit distances. The default is 0 mm horizontally and 6 mm vertically. |
tick_height, label_gap |
Non-negative absolute grid units or layout-unit numbers for the end ticks and space between the bar and caption. Physical conversion uses the current render context when available; device-free builds retain an explicitly estimated measurement status. |
linewidth, colour, size |
Fixed line colour/width and text size. Text size follows ordinary ggplot2 millimetres. These may also use normal mappings and scales when not supplied as fixed arguments. |
position, show.legend, inherit.aes |
Standard ggplot2 layer arguments. |
... |
Additional fixed aesthetics passed to |
Details
The bar does not claim to span one source interval. An explicit length can therefore exceed a single window and still be a valid distance reference in the shared linear metric. With no length, a small whole-number 1/2/5 reference is chosen from displayed window lengths. No source coordinates are modified and no missing genomic region is manufactured.
To change ticks and labels on sequence axes instead, use
scale_seq_position_continuous(). A position scale configures existing
axes; this geom adds an independent distance reference.
Value
One independent ggplot2 layer. Exported axis geometry retains the
length, sequence unit, input row and measurement status for each bar.
The compatibility field bp_length is NA for protein plots.
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
ggchord(seq_data = seqs) +
geom_seq() +
coord_collinear() +
geom_seq_scale(length = 10000)
Draw a sequence-local data layer with ggplot2 grammar
Description
Statistics and data positions are calculated independently within each accession/window before projection into the physical track band. Supported geoms are point, line, path, step, col, bar, tile, rect, area, ribbon, segment, linerange, errorbar and text. Supported statistics are identity, count, bin, summary, smooth, density and ecdf; unsupported combinations fail in the native layer. Smooth/density/ecdf retain each estimation group's complete eligible source-row set, not new independent observations. These sets describe the group submitted to the native estimator, not per-point influence or a custom model's additional internal filtering decisions. Statistics operate on raw source x/y before Track numerical-scale transforms. ECDF requires explicit pad=FALSE because infinite anchors are not source positions. Density's native bounds argument is not forwarded: bounds here controls source-coordinate clipping, not density boundary correction. New estimation combinations use position="identity": smooth with line/path/point/ribbon, density with line/path/point/area, and ecdf with line/path/point/step. Other combinations are explicitly rejected. Count counts identical positions; bin requires explicit binwidth or breaks. An explicit group mapping takes priority over discrete style mappings. Bin source membership follows the native statistic, including outer edges and its numerical boundary tolerance, before data positions move the bars. Mapping x/y refers to source position/local numerical value, not screen x/y. Existing track_value/track_fill/track_colour roles remain accepted.
Usage
geom_track_bar(
mapping = NULL,
data = NULL,
position = NULL,
baseline = 0,
fill = "#86AFB9",
colour = NA,
alpha = 1,
linewidth = 0.25,
linetype = 1,
bounds = c("error", "clip"),
show.legend = NA,
inherit.aes = FALSE,
...
)
geom_track(
mapping = NULL,
data = NULL,
geom = "point",
stat = NULL,
track = NULL,
position = NULL,
bounds = c("error", "clip"),
baseline = 0,
show.legend = NA,
inherit.aes = FALSE,
...
)
geom_track_col(
mapping = NULL,
data = NULL,
position = NULL,
track = NULL,
...,
show.legend = NA,
inherit.aes = FALSE
)
Arguments
mapping, data |
Standard layer input. Supply accver and source positions through x/pos, or interval start/end. Map y/track_value for identity values. |
position |
Data position such as identity, stack, dodge. The legacy position=position_track(...) spelling still declares the physical band. |
baseline |
Numeric identity-column baseline. Nonzero baselines require position='identity' so stacking does not change their meaning. |
fill, colour, alpha, linewidth, linetype |
Fixed styles for the count shortcut. |
bounds |
Coordinate error/clip policy. |
show.legend, inherit.aes |
Standard layer controls. |
... |
Native geom/stat parameters and fixed styles. |
geom, stat |
Native geometry/statistic names. bar defaults to count; col and other geoms default to identity. |
track |
A physical |
Value
A ggplot2 layer using a shared sequence-local band.
Examples
# Synthetic observations illustrate counting, not biological measurements.
events <- data.frame(accver = "A", pos = c(100, 100, 400))
ggchord(data.frame(accver = "A", length = 1000)) +
geom_seq() +
geom_track(data = events, geom = "bar", track = position_track("count")) +
coord_collinear()
# Fit existing GC windows in source space; estimates are not new data.
path <- system.file("extdata", "pUC19-gc-100.bedGraph", package = "ggchord")
signal <- read_bedgraph(path)
signal$pos <- (signal$start + signal$end) / 2
ggchord(data.frame(accver = "pUC19", length = 2686)) +
geom_seq() +
geom_track(aes(x = pos, y = value), data = signal, geom = "line",
stat = "smooth", method = "lm", formula = y ~ x, se = FALSE,
track = position_track("GC")) +
coord_collinear()
Draw explicit quantitative tracks along sequence backbones
Description
Tiles require accver, start, end; lines require accver
and pos. Map track_value for numeric height and track_fill or
track_colour for visual mapping. Values are never inferred from column
names. group separates line series; positions must increase strictly
within each sequence/series. NA height breaks lines and never
becomes zero. Inf is rejected. Tiles may overlap in input drawing order;
no averaging, interpolation or implicit aggregation is performed.
Usage
geom_track_tile(
mapping = NULL,
data = NULL,
position,
fill = "#86AFB9",
colour = NA,
alpha = 1,
linewidth = 0.25,
linetype = 1,
bounds = c("error", "clip"),
show.legend = NA,
inherit.aes = FALSE,
...
)
geom_track_line(
mapping = NULL,
data = NULL,
position,
colour = "#387D88",
alpha = 1,
linewidth = 0.4,
linetype = 1,
closed = FALSE,
bounds = c("error", "clip"),
show.legend = NA,
inherit.aes = FALSE,
...
)
Arguments
mapping, data |
Standard ggplot2 mapping and layer input. |
position |
A |
fill, colour, alpha, linewidth, linetype |
Fixed styles; fill and colour mappings use the dedicated track roles and scoped scales. |
bounds |
|
show.legend, inherit.aes |
Standard layer arguments. |
... |
Extra geom parameters. |
closed |
Explicitly close a complete circular line series. |
Details
All coordinates are window-local, one-based inclusive.
Interval bins occupy their full end - start + 1 bases, including one-base
bins; line samples use the specified positions without binning.
Use
focus_ggchord_track() for source windows. Lines never connect distinct
windows, even when they share a display row. Circular lines close only with
explicit closed = TRUE; missing endpoints are not joined across NA.
Value
A ggplot2 layer with independent input and a shared named band.
Examples
library(ggchord)
library(dplyr)
data(plasmid_example_pUC19)
track_seq <- plasmid_example_pUC19 |>
select(accver, length)
starts <- seq.int(1L, track_seq$length, by = 100L)
gc_fraction <- function(sequence) {
bases <- strsplit(sequence, "")[[1]]
mean(bases %in% c("G", "C"))
}
bins <- tibble(
accver = track_seq$accver,
start = starts,
end = pmin(starts + 99L, track_seq$length)
) |>
rowwise() |>
mutate(gc = gc_fraction(substr(plasmid_example_pUC19$sequence, start, end))) |>
ungroup()
doc_theme <- theme_ggchord_publication(
axis.text = element_text(size = 9), axis.text.check.overlap = TRUE
) +
theme(legend.position = "bottom")
p_tracks <- ggchord(seq_data = track_seq) +
geom_seq() +
geom_seq_center_label() +
geom_track_col(aes(track_value = gc, track_fill = gc),
data = bins,
position = position_track("gc", width = unit(6, "mm"))
) +
scale_track_value_continuous("gc", limits = c(0, 1), unit = "GC fraction") +
scale_track_fill_gradientn("gc", colours = c("#EDF1EA", "#8AAE9C", "#345F58")) +
coord_circular() +
doc_theme
Get the chord layout from a ggchord plot
Description
Returns the layout owned by an explicit ggchord plot. This avoids ambiguous
cross-talk when several plots are built in one R session.
For layer-aware tabular results, prefer export_ggchord_layout(). See
ggchord_layout_contract for fields, units and cache ownership.
Device/context changes invalidate cached estimates, including ordinary
label layouts. build = FALSE then reports that no current layout is cached.
Usage
get_chord_layout(plot, build = TRUE)
Arguments
plot |
A ggchord plot. |
build |
Logical. Build the layout when it is not cached, default TRUE. |
Value
A chord layout list containing the computed geometry (sequence arcs, ribbon polygons, gene arrows, axis elements, extremes, colors, etc.)
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
p <- ggchord(seq_data = seqs) +
geom_seq()
get_chord_layout(p)$seqs
Layered chord, circular and collinear sequence plots
Description
Visualize multi-sequence alignments, a single circular sequence or linear
collinearity using ggplot2's layered grammar. The constructor supplies data
and validation. Add geometry with geom_*(), select a global view with
coord_chord(), coord_circular() or coord_collinear(), and use
mappings/scales for data-driven styles and themes for non-data appearance.
The layout is computed lazily when the plot is built (e.g. via print(),
ggsave(), or ggplot_build()).
Usage
ggchord(
seq_data,
ribbon_data = NULL,
gene_data = NULL,
debug = FALSE,
validate = c("warn", "error", "none"),
feature_data = NULL,
...
)
Arguments
seq_data |
data.frame/tibble with accver and length, or a |
ribbon_data |
Optional alignment table with qaccver, saccver, qstart,
qend, sstart and send. length and pident are optional unless requested
by a mapping, filter or statistic. A |
gene_data |
Compatible legacy annotation input. The third positional
argument retains its meaning. Use |
debug |
Logical. Whether to output debug information, default FALSE |
validate |
Character, default |
feature_data |
Optional unified annotation table or |
... |
Reserved for clear migration errors from removed constructor
arguments. Use |
Value
A ggchord object (inherits from ggplot) to which geom_* layers can be added with +
See Also
ggchord_api_contract, ggchord_data_contract,
ggchord_layout_contract, view_ggchord()
Examples
library(dplyr)
library(ggchord)
data(seq_data_example)
data(ribbon_data_example)
data(gene_data_example)
seqs <- seq_data_example |>
select(accver, length)
links <- ribbon_data_example |>
select(qaccver, saccver, qstart, qend, sstart, send)
genes <- gene_data_example |>
transmute(accver, start, end, strand = source_strand, type = "CDS")
p <- ggchord(
seq_data = seqs,
ribbon_data = links,
feature_data = genes
) +
geom_seq() +
geom_link_ribbon() +
geom_gene()
print(p)
Current API and migration contract
Description
The current development API defines plotting, data and output contracts. The v0.16.4 candidate freeze is a historical development baseline, not a claim of v1.0.0 compatibility or complete platform/device validation. Correctness fixes remain possible with documented evidence and migration.
Plotting responsibilities
ggchord() supplies reference sequences and optional default input tables.
Each layer retains its own data, mapping, parameters and identity. aes()
selects data roles, scales control mapping rules/guides, geoms draw entities,
Positions place them locally, coords select the canvas mode, and themes
control non-data appearance. Explicit fixed styles take precedence over
matching mappings; omit a fixed argument to retain its mapping. User scales
take precedence over automatically inferred defaults.
geom_gene() remains the strictly directed gene shortcut over the generic
geom_feature() constructor. Unknown-strand features remain unknown and
use the generic feature entrance. The plasmid shortcut retains its distinct
defaults. Fixed feature shape is shape; mapped shape is feature_shape.
Gene/feature widths use width, label controls use label_*, and point/area
links use link_gap and link_ctrl_point. These names do not merge the
distinct geometries or their defaults.
Chord, collinear, radial synteny, Sankey, circular and Dotplot are six
coordinate modes. Fusion composes independently registered plots and is not
a coordinate mode. Dotplot requires its dedicated alignment segment layer
and is not a registered Fusion endpoint. Circular
maps reject ribbon and point-link layers; collinear maps reject
restriction/primer/centre-label layers. geom_seq_scale() is a collinear
sequence-unit reference bar; scale_seq_position_continuous() configures genomic axes.
A matching name never implies that every geom supports every coord.
Names and migration errors
The colour spelling is preferred in documentation; existing color
spelling aliases remain supported. Selected ggplot2/grid reexports retain
the original upstream object and follow that dependency's public contract.
Their internals and future upstream signatures are not frozen by ggchord.
Retired arguments remain errors with replacement guidance; they do not
execute compatibility code. In v0.16.1, fixed feature_shape, old width,
label and ribbon endpoint names were removed in favour of the names above.
gene_offset/feature_offset were also removed then; use
position = position_strand(offset = ...). Explicit strand-named offsets
are signed, so negate the former minus-strand magnitude when migrating it.
The old v1.0.0 removal deadline no longer applies.
Automatic gene/feature labels own their rotation, offsets, orientation and
overlap policy. Manual label_rotation, label_radial_offset,
label_circum_offset, label_circum_limit, label_orientation and
label_overlap supplied through their ... now fail rather than being
ignored. Use geom_gene_label() or geom_feature_label() for manual
placement, or choose automatic geometry with label_layout.
The old "aligned" label request becomes label_layout = "auto";
restriction leader = "trunk" becomes leader = "radial".
Constructor unknown arguments stop. Ordinary geom, scale, guide and theme
extras retain their documented forwarding and upstream error/warning rules;
there is no promise that all unknown names fail uniformly. Geometric roles
must be evaluated before layout, whereas supported visual mappings may use
after_stat()/after_scale(). Unknown legacy label prefixes never imply
that a similarly named replacement parameter exists.
Data, units and results
Input accver and query/subject identifiers are preserved without adding or
removing versions. Biological strand, display orientation and link direction
remain distinct. Coordinates are one-based inclusive in the declared native
bp or aa units after explicit
external-format adaptation. Missing values, defaults and NULL are defined
per responsibility, not by one package-wide coercion rule.
Standalone cleaning defaults to sorting reversed endpoints; preparation
retains direction by default. Readers retain file/files with shared
path expansion. See ggchord_data_contract for source rows, optional
dependencies, transformations, aggregation estimates and search limits.
Native layout distances, sequence units, angles, numerical track domains and physical
mm are separate quantities. Track IDs share numerical domains and consistent
band declarations; their physical placement is not a numeric value scale.
Existing documented return members remain supported. Prefer
export_ggchord_layout() for layer-aware tables; get_chord_layout() remains
available for the complete layout. Preview paths and target-size diagnostic
reports retain separate purposes. See ggchord_layout_contract for stable
fields, provenance, measurement status and plot/render cache ownership.
See Also
ggchord_data_contract, ggchord_layout_contract
Examples
library(dplyr)
data(plasmid_example_pUC19)
seqs <- plasmid_example_pUC19 |>
select(accver, length)
feature_source <- find_common_features(plasmid_example_pUC19)
features <- feature_source |>
select(accver, start, end, strand, type, anno)
# ASCII display copy for the default PDF help-example device.
features <- features |>
mutate(anno = gsub("\u03b1", "alpha", anno, fixed = TRUE))
p <- ggchord(seq_data = seqs) +
geom_seq() +
geom_feature(data = features) +
coord_circular()
export_ggchord_layout(p, include = "feature")$metadata$coordinate
Data workflow and biological coordinate contracts
Description
ggchord separates reading, adaptation, validation, explicit cleaning and preparation. None of these steps runs BLAST, infers a missing full sequence length from features, verifies homology experimentally, or adds plot layers.
Details
- Read
The
read_*()functions parse local files. Bothfileandfiles, when both are exposed by a reader, accept path vectors and glob patterns. When both are supplied,fileprecedesfiles; matches expand in pattern order, and each normalized path is read once, retaining its first supplied spelling. Missing, empty, unmatched or directory paths fail. Text input must be UTF-8 (an initial BOM is accepted by table readers). Convert other encodings explicitly before reading. Import attributes record format, files and output counts. Tabular readers and FASTA lengths retain physical.source_line; optional.source_filegives row-level file identity. GenBank instead retains record/feature indices and source text in its report. Malformed field counts stop, rather than shifting fields between rows. Numeric conversion problems in BLAST/GFF3 warn and retain missing values for inspection and validation.- Adapt
as_ggchord_*()accepts documented tables or optional interval/sequence objects. Required IDs and positive integral coordinates are checked immediately; zero-based tables must be converted explicitly. Metadata name collisions receive prefixes and a column map. Required coordinate NA is an error, while unrelated metadata NA survives. Seqinfo, object metadata, names and upstream provenance are retained in the conversion attribute. Optional packages are never installed automatically.- Validate
validate_ggchord_data()reports all collected issues without changing input.strict = TRUEstops after collection if errors exist. Logical argument errors stop immediately. This validator describes constructor seq/ribbon/gene tables and the unifiedfeature_datainput, including unknown and bidirectional strands. Coordinate checks do not prove an alignment or a biological annotation.- Clean
clean_ggchord_data()explicitly applies selected policies and reports original rows and old/new values. Its historicalreversed_interval = "sort"is retained; use"keep"for directional links or circular-origin features. Sorting cannot recover their original meaning later. Unknown-ID"keep"is an audit policy, not a guarantee that the result is drawable. NULL means an absent optional table, and an empty table remains a table.- Prepare
prepare_ggchord_data()adapts first, validates, then runs only requested steps in the documented order. Its cleaning default isreversed_interval = "keep", because downstream operations use endpoint directions. Adaptation errors therefore occur before cleaning; clean/drop malformed IDs separately when needed. Named features/links remain independent collections. Reports distinguish stage-local rows from composed original ribbon source sets.
Coordinates and direction
ggchord(feature_data = ...) supplies default data for generic annotation
layers. Gene layers select explicitly classified gene/CDS records; tRNA/rRNA
and unclassified annotations remain generic features. Untyped legacy
gene_data retains its directional semantics. Do not provide both inputs.
Explicit layer data takes priority; mixed gene/feature compositions should
use disjoint data subsets. Independent layers do not remove each other's rows.
Native coordinates are one-based inclusive. Sequence tables may declare
sequence_unit = "bp" or "aa"; omitted units mean bp. A plot uses one unit.
Full protein lengths must be provided; alignment endpoints do not establish
full lengths. Protein annotations use generic feature layers. Gene, primer
and restriction layers require nucleotide input. A circular protein layout
is a visual arrangement and does not declare circular biological topology.
start == end is one base or one residue in the declared unit.
The explicit adapters enforce integral coordinates. Legacy constructor
validation, cleaning and raw focus accept finite numeric positions; their
success alone does not certify integral genomic coordinates. Prefer integral
windows for biological data and use adapters before these legacy entries
when strict integer checks are required.
BEDPE keeps first/second anchors as query/subject, preserves original fields,
and follows paired-object negative-strand endpoint ordering. It does not
infer identity or read support. Unknown anchors fail by default; the explicit
read_bedpe(unmapped = "keep") auditing policy retains missing canonical
coordinates and mapping flags. Filter complete anchors before adaptation or
plotting; keeping them is not evidence that they are drawable.
BED/PAF half-open [a,b) becomes [a+1,b]; zero-width records
cannot become nonempty intervals and are rejected. Link endpoint order can
encode relative direction; it is not a circular-origin join. Feature
start > end is context-dependent: circular plotting can split an origin
join, while linear window workflows require explicit ordered segments and an
envelope. A raw focus locus uses min/max of its bounds, not an origin wrap.
strand is biological annotation, orientation is display choice,
and link direction is relative. Single-base link endpoints have no
order: supplied strand or
relative direction can provide evidence, otherwise direction remains unknown.
Merge and bundle retain these rows independently instead of manufacturing
aggregate endpoint directions. Unknown orientation is kept separate from
known direction in density and deduplication.
Unknown strands remain unknown in
adapters; GFF3's explicit legacy unstranded = "plus" is an exception,
with source_strand retained. Prefer unstranded = "keep" and
generic feature layers when direction is unknown.
Plotting uses a continuous display axis, not a base-cell raster: feature/axis chord anchors use pos/length, point-link anchors use (pos-1)/length. These historical graphical offsets do not change stored coordinates. Single-base features can use a point or widened glyph. No new endpoint convention is imposed on plots in this data-workflow revision.
Selection, projection and aggregation
Focus crops all selected tables and composes earliest source coordinates.
Overlapping windows can copy a row. Ribbon clipping interpolates an endpoint
correspondence, rounds to bp and marks estimated length; identity is retained,
not recalculated. Segment preparation creates separate windows and explicit
gaps; it never concatenates their biological sequences. Position mapping is
invertible within the selected linear window and rejects segmented gaps.
translate_ggchord_cds() extracts real forward source strings through the
same CDS map and delegates translation to optional Biostrings. It requires
known genetic codes, retains stops, reports partial trimming and preserves
the three genomic positions of every codon.
register_ggchord_alignment() registers exact source/column cells for
independent Cartesian detail panels, without deriving any bases from HSPs.
CDS projection uses observed complete codons and explicit phase/partial
policies; it does not translate with the stored genetic-code ID. Protein
identity/length remain source-prefixed metadata when links are projected.
Filtering retains full rows. Deduplication selects representatives and
reports discarded rows; it does not combine their statistics. Merge creates
envelopes and reports source sets, lengths and identities. Bundle groups by
pair, relative endpoint direction and midpoint bins; both endpoints may be
reversed together in one group. Envelope endpoints follow the first row's
absolute direction. Bundle length is a rounded length-weighted mean of source
lengths, identity is a length-weighted mean, and conflicting extra metadata
become typed NA. These summaries are not new alignments. Supply
group_by for metadata that must remain separate. Density retains every
input row and measures bin weight relative to that pair's maximum bin; it
is not coverage or statistical probability. Optimization suggests display
order/orientation without changing biological strand or query/subject roles.
Search helpers
Cluster links use declared membership, with explicit paralog and segment
policies, not sequence alignment. Primer exact and three-prime suffix searches
report zero mismatches; a partial suffix is not full-oligo validation. Wallace
temperature is a simple composition estimate, not an experimental prediction.
Restriction results are motif matches and source-backed cut offsets; missing
cuts remain unknown. Methylation status uses supplied/reference context and a
limited sensitivity catalogue, not a complete digestion model. Linear context
never wraps sequence ends. Common-feature confidence is a deterministic
heuristic rank, not a probability or experimental confirmation. Its six-frame
protein search uses the standard codon table without alternative starts,
splicing or circular-origin protein matches. Source geneticCode
metadata is not interpreted as a selectable translation table. Use exact DNA
mode or an external code-aware analysis for nonstandard translation.
Character alignments
read_aligned_fasta() is a single-alignment, single-file reader; it does
not concatenate independent alignments or expose a files argument.
as_ggchord_alignment() distinguishes alignment columns from nullable
source positions. Gaps consume columns only. Default positions refer to
ungapped input fragments, not complete genomes. Explicit source metadata
can verify supplied characters; it does not independently establish homology.
map_alignment_position() performs exact lookups without interpolation.
geom_residue() draws local cells in ordinary Cartesian ggplots, outside
the biological backbone Coord pipeline. No new alignment is computed.
See Also
prepare_ggchord_data, read_genbank,
as_ggchord_feature, project_ggchord_links
Compose independent genomic panels
Description
A Fusion is a static composition, not a coordinate system. Add independent
fusion_panel() objects and independent fusion_ribbon() layers. Ordinary
ggplot2::ggsave() rebuilds panels and interval fronts at the target size.
Source plots and their scales remain independent. Composition scales and
themes apply to cross-panel links, their separate Guides and native outer
plot furniture. Use labs(title/subtitle/caption/tag) and standard plot Theme
elements for composition headings, captions, backgrounds and margins. Child
axes and styles remain local; the composition has no Cartesian data axes.
Usage
ggchord_fusion(
center,
center_size = NULL,
layout = c("fixed", "adaptive"),
allow_overlap = FALSE,
center_box = NULL,
guides = c("keep", "collect")
)
Arguments
center |
A ggchord genomic plot (Circular, Chord, Collinear, Sankey or Radial), or another Fusion. Nested biological endpoints use full panel paths. |
center_size |
Optional width and height as fractions of the composition content area, excluding native outer plot decorations and cross-panel Guides. NULL allocates available space. |
layout |
|
allow_overlap |
Explicitly allow container overlap. Default FALSE fails on overlap. When TRUE, later panels paint over earlier panels. Connections use disjoint native grid clips to avoid accumulating translucent fills. Ordinary child margins do not break links; later containers still cover earlier content. This is deliberate placement, not global collision avoidance. |
center_box |
Optional centre allocation: xmin, xmax, ymin, ymax as four fractions of the composition content area excluding outer decorations and Guides, or four absolute grid units. Use instead of center_size. See fusion_panel(). |
guides |
|
Value
A Fusion object, printable and accepted by ggplot2::ggsave().
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |> select(accver, length) |> slice_head(n = 2)
center <- ggchord(seqs) + geom_seq() + coord_chord()
detail <- ggchord(seqs) + geom_seq() + coord_collinear(seq_axis = "vertical")
ggchord_fusion(center, guides = "collect") +
fusion_panel(detail, id = "detail", side = "right") +
ggplot2::labs(title = "Independent genomic views",
caption = "Source: bundled sequence records")
Layout results, units and ownership
Description
export_ggchord_layout() is the recommended interface for consuming
layer-aware geometry tables. get_chord_layout() retains the complete
layout list and its documented geometry, bounds, colour and label members.
Neither entrance is deprecated. view_ggchord() returns a temporary image
path; diagnose_ggchord() returns evidence for one requested render.
Geometry and provenance
Selected export components are data frames; absent components may be empty
data frames without columns. Nonempty geometry has layer_id, component
and source_row. An ID identifies one layer occurrence in that plot;
editing/reordering layers can change IDs. A source row indexes the resolved
input for that layer/component, not necessarily a physical file line.
Generated decorations use missing source rows. Aggregates may carry
source_rows membership instead of identifying one observation.
original_data = TRUE includes resolved inputs for selected nonempty
components, after role mapping and input adaptation. It is not a raw-file
archive. File line/record provenance and conversion attributes retain their
separate meanings from ggchord_data_contract.
Cartesian geometry and bounding boxes use native layout data units.
Genomic source coordinates remain one-based inclusive bp; they are not
converted to Cartesian distances. Angles use degrees except explicitly
internal sequence-reference angles. Text sizes use mm. Metadata retains
coordinate_space, units, coordinate, rotation, rotation_applied,
coord_transform_applied, ratio, fit, xlim, ylim and clip.
Exported coordinates already include layout rotation, before the ggplot2
coord transform. Native data units are not millimetres or genomic bp.
Coordinate-specific tables
source_registry identifies constructor source rows without adding reserved
columns to user data. layer_sources maps annotation input_row to its
source ID, table and row; geometry source_row still indexes the resolved
layer input. Default annotation layers share constructor source IDs. Explicit
layer tables and data functions have layer-local scope; content equality is
not used to guess shared identity. IDs are local to the plot, not persistent
file identifiers. annotation_duplicates reports constructor annotations
rendered by more than one geometry layer; labels do not count as duplicates.
Circular annotation_registry retains its documented identity, owner,
component/source row, inner track/radius/width/boundaries, outer region,
sector, band, dominant band, slot, spill reason, crossing count, bounding box
and leader corridor fields. Radii, widths and boxes use layout data units;
tracks/slots are build-local resource indices. Missing values denote fields
that do not apply. These resources are distinct from named quantitative
track IDs and Position lanes.
Collinear sequence_layout retains reversible window/source origins,
horizontal range, backbone y, display orientation, units per bp, x offset
and anchor. Segmented rows also retain row/window order, breaks and display
gap_bp; omitted gaps have no source mapping. orientation_diagnostics,
connection_report and label_diagnostics retain support, selection and
placed/hidden-label evidence, including layer/row provenance where applicable.
track_registry retains track ID, accession, placement, source layers,
numerical limits in original value units, optional unit, domain status
and measurement status. Native offsets/widths use layout units; _mm
fields are physical mm contributions. normal_min/normal_max use layout
units. track_diagnostics records input rows, retention/reason, coordinate
clipping and the original bar baseline. axis_selection records selected
sequence axes. label_fit_diagnostics retains original text, requested,
minimum/final sizes in mm and fallback/hiding reasons. Empty diagnostic
tables need not have a fixed column prototype.
Dotplot and radial frames
Dotplot axis_layout records one frame per axis/accession with length,
offset, direction, source origin and native unit. Display gaps have no source
mapping. alignment retains all four HSP positions; it is not a fine-grained
alignment trace. A declared unknown direction is omitted and reported.
Radial radial_frames exposes local tangent/normal vectors, angle and inner
radius. radial_endpoints retains both original positions and ordered closed
interval boundaries, with their final endpoint coordinates. Position mapping
uses one-based native positions; interval fronts use [min-1,max] boundaries.
Radial adjacency is cyclic display topology, never biological closure or
evidence of a missing relationship. Native track statistics remain computed
before instance replication and view projection.
Measurement and cache scope
render_context and diagnostic measurement distinguish estimated,
unavailable and measured panel status. panel_mm, canvas_mm and,
when measured, panel_bounds_mm use physical mm. units_per_mm and
axis_units_per_inch convert layout units along x/y; units_per_inch is
a conservative scalar text metric. geometry_metric_status and converged
describe refinement accuracy separately from panel measurement. Estimated
contexts can have missing dimensions and convergence. Device/basis/font
conditions state the source and limits of the evidence. Refinement counts
and private solver/candidate/cache structures are implementation details.
With adapt_ggchord(), layout-only exports report adaptive_layout$policy
and mark the guide layout as target_device_required. Target-size diagnostics
instead report effective theme styles, scale factors and a guide_layout
with selected grids, explicit locks, candidate sizes and final guide-box
bounds in mm. Search indices and scores are diagnostic details, not stable
biological identifiers. A feasible guide budget is not a global collision
certificate. Fusion exposes these reports separately for each panel.
A plot composition owns a fresh layout cache; a build/getter may populate
it. Device/context changes invalidate estimates, even for ordinary labels.
get_chord_layout(build = FALSE) requires a current cache. Previews and
diagnostics render independent copies and preserve the source cache.
Reference-path reuse lasts only for one geometry calculation. Temporary
render contexts restore their predecessor on normal or exceptional exit.
Ordinary R assignment retains ggplot2 reference semantics for ggproto
objects; arbitrary direct mutation of shared layer environments is not
tracked as a new plot composition.
Stability and diagnostic limits
Existing documented members above remain supported. Additional columns may be attached for input metadata or geometry-specific needs; consumers should select named fields, not fixed column positions/counts. Numeric layouts can change with size, device, font and legitimate collision handling. Resource numbers and diagnostic reason details are not persistent biological IDs. No candidate layout, private cache or iteration count is a stable result.
Diagnostics retain measurement, checks, text, guides,
colour_suggestions, label_diagnostics, annotation_registry,
track_registry, track_diagnostics and warnings. Text/guide bounds and
line/text sizes use mm; colour distances use the named model in each row.
A measured panel does not certify collision-free geometry, font embedding,
fallback, arbitrary grobs or cross-application portability. Preview paths
live in a temporary directory and may be removed by cleanup; use ordinary
ggplot2::ggsave() to keep a final file.
label_quality adds measured panel text/annotation-leader contacts, source
visibility counts and text/leader tables. Oriented boxes and leader lengths
use mm; arc glyphs share a text-object identity. Counts are evidence within
the stated scope, not exact ink outlines or a certificate for text-feature
contacts, custom grobs or external plot decorations. Unchecked metrics stay
missing, and diagnostics do not change the layout or its original records.
Foundation projection and identity
display_instances separates source accver from instance_id and display
order. instance_routing identifies each source HSP and its unique query/
subject display route. Explicit source_hsp_id is shared across layers;
absent IDs are layer-local. Routing retained records whether a relation
survives geometry selection; repeated_display and repeated-ID checks use
only retained source observations, including ordinary views without copies.
sequence_display records source_length,
display_length and display_scale_factor; equal allocation changes only the
display projection. Vertical Collinear uses final y as its inverse axis.
Sankey instances additionally record left/right side; query is always left.
track_statistics retains computed values and source_rows before display
replication; track_source_data is included with original_data=TRUE.
label_visibility reports layer/component/source_row, visibility, policy
reason, final position and size, and available perimeter/crossing fields.
An unavailable collision field is NA, never evidence of zero collisions.
See Also
ggchord_data_contract, export_ggchord_layout(),
get_chord_layout(), view_ggchord(), diagnose_ggchord()
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
p <- ggchord(seq_data = seqs) +
geom_seq()
geometry <- export_ggchord_layout(p, include = "seq")
geometry$seq |>
distinct(layer_id, component, source_row)
Selected ggplot2 helpers for ggchord plots
Description
ggchord re-exports a deliberately small set of ggplot2 helpers that are directly useful when constructing, annotating, styling, or saving a chord plot. Cartesian geoms, coordinates, facets, generic scales, and complete theme presets remain in ggplot2 so IDE completion stays focused.
Usage
aes(x, y, ...)
after_stat(x)
after_scale(x)
annotate(
geom,
x = NULL,
y = NULL,
xmin = NULL,
xmax = NULL,
ymin = NULL,
ymax = NULL,
xend = NULL,
yend = NULL,
...,
na.rm = FALSE
)
labs(
...,
title = waiver(),
subtitle = waiver(),
caption = waiver(),
tag = waiver(),
dictionary = waiver(),
alt = waiver(),
alt_insight = waiver()
)
ggtitle(label, subtitle = waiver())
guides(...)
theme(
...,
line,
rect,
text,
title,
point,
polygon,
geom,
spacing,
margins,
aspect.ratio,
axis.title,
axis.title.x,
axis.title.x.top,
axis.title.x.bottom,
axis.title.y,
axis.title.y.left,
axis.title.y.right,
axis.text,
axis.text.x,
axis.text.x.top,
axis.text.x.bottom,
axis.text.y,
axis.text.y.left,
axis.text.y.right,
axis.text.theta,
axis.text.r,
axis.ticks,
axis.ticks.x,
axis.ticks.x.top,
axis.ticks.x.bottom,
axis.ticks.y,
axis.ticks.y.left,
axis.ticks.y.right,
axis.ticks.theta,
axis.ticks.r,
axis.minor.ticks.x.top,
axis.minor.ticks.x.bottom,
axis.minor.ticks.y.left,
axis.minor.ticks.y.right,
axis.minor.ticks.theta,
axis.minor.ticks.r,
axis.ticks.length,
axis.ticks.length.x,
axis.ticks.length.x.top,
axis.ticks.length.x.bottom,
axis.ticks.length.y,
axis.ticks.length.y.left,
axis.ticks.length.y.right,
axis.ticks.length.theta,
axis.ticks.length.r,
axis.minor.ticks.length,
axis.minor.ticks.length.x,
axis.minor.ticks.length.x.top,
axis.minor.ticks.length.x.bottom,
axis.minor.ticks.length.y,
axis.minor.ticks.length.y.left,
axis.minor.ticks.length.y.right,
axis.minor.ticks.length.theta,
axis.minor.ticks.length.r,
axis.line,
axis.line.x,
axis.line.x.top,
axis.line.x.bottom,
axis.line.y,
axis.line.y.left,
axis.line.y.right,
axis.line.theta,
axis.line.r,
legend.background,
legend.margin,
legend.spacing,
legend.spacing.x,
legend.spacing.y,
legend.key,
legend.key.size,
legend.key.height,
legend.key.width,
legend.key.spacing,
legend.key.spacing.x,
legend.key.spacing.y,
legend.key.justification,
legend.frame,
legend.ticks,
legend.ticks.length,
legend.axis.line,
legend.text,
legend.text.position,
legend.title,
legend.title.position,
legend.position,
legend.position.inside,
legend.direction,
legend.byrow,
legend.justification,
legend.justification.top,
legend.justification.bottom,
legend.justification.left,
legend.justification.right,
legend.justification.inside,
legend.location,
legend.box,
legend.box.just,
legend.box.margin,
legend.box.background,
legend.box.spacing,
panel.background,
panel.border,
panel.spacing,
panel.spacing.x,
panel.spacing.y,
panel.grid,
panel.grid.major,
panel.grid.minor,
panel.grid.major.x,
panel.grid.major.y,
panel.grid.minor.x,
panel.grid.minor.y,
panel.ontop,
panel.widths,
panel.heights,
plot.background,
plot.title,
plot.title.position,
plot.subtitle,
plot.caption,
plot.caption.position,
plot.tag,
plot.tag.position,
plot.tag.location,
plot.margin,
strip.background,
strip.background.x,
strip.background.y,
strip.clip,
strip.placement,
strip.text,
strip.text.x,
strip.text.x.bottom,
strip.text.x.top,
strip.text.y,
strip.text.y.left,
strip.text.y.right,
strip.switch.pad.grid,
strip.switch.pad.wrap,
complete = FALSE,
validate = TRUE
)
element_blank()
element_line(
colour = NULL,
linewidth = NULL,
linetype = NULL,
lineend = NULL,
color = NULL,
linejoin = NULL,
arrow = NULL,
arrow.fill = NULL,
inherit.blank = FALSE,
size = deprecated(),
...
)
element_rect(
fill = NULL,
colour = NULL,
linewidth = NULL,
linetype = NULL,
color = NULL,
linejoin = NULL,
inherit.blank = FALSE,
size = deprecated(),
...
)
element_text(
family = NULL,
face = NULL,
colour = NULL,
size = NULL,
hjust = NULL,
vjust = NULL,
angle = NULL,
lineheight = NULL,
color = NULL,
margin = NULL,
debug = NULL,
inherit.blank = FALSE,
...
)
margin(t = 0, r = 0, b = 0, l = 0, unit = "pt", ...)
rel(x)
ggsave(
filename,
plot = get_last_plot(),
device = NULL,
path = NULL,
scale = 1,
width = NA,
height = NA,
units = c("in", "cm", "mm", "px"),
dpi = 300,
limitsize = TRUE,
bg = NULL,
create.dir = FALSE,
...
)
last_plot()
waiver()
expansion(mult = 0, add = 0)
position_identity()
PositionIdentity
Arguments
x, y |
Aesthetic expressions for mappings; x is also the staged expression or relative size, depending on the helper. |
... |
Additional named mappings, guide specifications, theme elements, fixed annotation aesthetics or device arguments, as appropriate for the called helper. |
geom, xmin, xmax, ymin, ymax, xend, yend, na.rm |
For annotate(), the geometry name, positional bounds and endpoints, and whether missing values are removed silently. In theme(), geom instead sets geometry defaults. |
title, subtitle, caption, tag, dictionary, alt, alt_insight, label |
Plot labels, title, subtitle, caption and tag; dictionary replaces variable labels and alt/alt_insight provide accessible descriptions. In theme(), title supplies inherited title styling. |
line, rect, text, point, polygon, spacing, margins, aspect.ratio, axis.title, axis.title.x, axis.title.x.top, axis.title.x.bottom, axis.title.y, axis.title.y.left, axis.title.y.right, axis.text, axis.text.x, axis.text.x.top, axis.text.x.bottom, axis.text.y, axis.text.y.left, axis.text.y.right, axis.text.theta, axis.text.r, axis.ticks, axis.ticks.x, axis.ticks.x.top, axis.ticks.x.bottom, axis.ticks.y, axis.ticks.y.left, axis.ticks.y.right, axis.ticks.theta, axis.ticks.r, axis.minor.ticks.x.top, axis.minor.ticks.x.bottom, axis.minor.ticks.y.left, axis.minor.ticks.y.right, axis.minor.ticks.theta, axis.minor.ticks.r, axis.ticks.length, axis.ticks.length.x, axis.ticks.length.x.top, axis.ticks.length.x.bottom, axis.ticks.length.y, axis.ticks.length.y.left, axis.ticks.length.y.right, axis.ticks.length.theta, axis.ticks.length.r, axis.minor.ticks.length, axis.minor.ticks.length.x, axis.minor.ticks.length.x.top, axis.minor.ticks.length.x.bottom, axis.minor.ticks.length.y, axis.minor.ticks.length.y.left, axis.minor.ticks.length.y.right, axis.minor.ticks.length.theta, axis.minor.ticks.length.r, axis.line, axis.line.x, axis.line.x.top, axis.line.x.bottom, axis.line.y, axis.line.y.left, axis.line.y.right, axis.line.theta, axis.line.r, legend.background, legend.margin, legend.spacing, legend.spacing.x, legend.spacing.y, legend.key, legend.key.size, legend.key.height, legend.key.width, legend.key.spacing, legend.key.spacing.x, legend.key.spacing.y, legend.key.justification, legend.frame, legend.ticks, legend.ticks.length, legend.axis.line, legend.text, legend.text.position, legend.title, legend.title.position, legend.position, legend.position.inside, legend.direction, legend.byrow, legend.justification, legend.justification.top, legend.justification.bottom, legend.justification.left, legend.justification.right, legend.justification.inside, legend.location, legend.box, legend.box.just, legend.box.margin, legend.box.background, legend.box.spacing, panel.background, panel.border, panel.spacing, panel.spacing.x, panel.spacing.y, panel.grid, panel.grid.major, panel.grid.minor, panel.grid.major.x, panel.grid.major.y, panel.grid.minor.x, panel.grid.minor.y, panel.ontop, panel.widths, panel.heights, plot.background, plot.title, plot.title.position, plot.subtitle, plot.caption, plot.caption.position, plot.tag, plot.tag.position, plot.tag.location, plot.margin, strip.background, strip.background.x, strip.background.y, strip.clip, strip.placement, strip.text, strip.text.x, strip.text.x.bottom, strip.text.x.top, strip.text.y, strip.text.y.left, strip.text.y.right, strip.switch.pad.grid, strip.switch.pad.wrap, complete, validate |
Theme elements and layout settings. Line, rectangle and text elements control appearance; spacing and margins use physical units, positions and justifications control placement. More specific axis, legend, panel, plot and strip elements inherit from their parents. complete marks a complete theme; validate checks element types. Consult ggplot2::theme for each element and its accepted values. |
colour, linewidth, linetype, lineend, color, linejoin, arrow, arrow.fill, inherit.blank, size, fill, family, face, hjust, vjust, angle, lineheight, margin, debug |
Element styling: colours, fill, line width and type, line ends and joins, arrows, font family/face/size, alignment, angle, line spacing and text margins. inherit.blank follows blank parent elements; debug shows text bounds. size for line/rectangle elements is deprecated upstream; use linewidth. |
t, r, b, l, unit |
Top, right, bottom and left margins and their physical unit. |
filename, plot, device, path, scale, width, height, units, dpi, limitsize, bg, create.dir |
Save settings: destination filename/path, plot, device, scale multiplier, width/height and units, raster resolution, size limit, background and permission to create the directory. |
mult, add |
Multiplicative and additive scale expansion, each a single value or lower/upper pair. |
Details
Mapping helpers are aes(), after_stat() and after_scale();
ggplot2::stage() combines stages of one aesthetic. Use labs() and
ggtitle() for titles, guides() for guide selection, and theme() with
the element_*() helpers for appearance. annotate() adds fixed annotations.
margin() and rel() specify theme sizes; waiver() and expansion()
specify automatic or expanded scale settings. position_identity() and
PositionIdentity are the upstream identity placement helpers.
ggsave() saves a supplied plot; last_plot() retrieves ggplot2's last plot.
Each symbol is the original ggplot2 function or object, and can also be
called with its ggplot2:: namespace. unit() and arrow() come from grid.
Physical units and direction arrows
Description
These are the original grid functions, available after loading ggchord. Use physical units for theme spacing and arrows for point links.
Usage
unit(x, units, data = NULL)
arrow(angle = 30, length = unit(0.25, "inches"), ends = "last", type = "open")
Arguments
x |
Numeric unit values. |
units |
Unit names, such as mm, inches or npc. |
data |
Optional supplementary data for special grid units. |
angle |
Arrow-head angle in degrees. |
length |
Arrow-head length as a unit object. |
ends |
Which ends receive arrows: first, last or both. |
type |
Arrow-head style: open or closed. |
Value
A grid unit or arrow object.
Examples
unit(2, "mm")
arrow(length = unit(2, "mm"), type = "closed")
Guides for ggchord role aesthetics
Description
Thin wrappers around ggplot2::guide_legend() and
ggplot2::guide_colourbar() with compact defaults suitable for
chord diagrams. All ordinary ggplot2 guide arguments remain available.
Usage
guide_ggchord_legend(
title = ggplot2::waiver(),
theme = NULL,
position = NULL,
direction = NULL,
override.aes = list(),
nrow = NULL,
ncol = NULL,
reverse = FALSE,
order = 0,
size_scale = 1,
...
)
guide_ggchord_colourbar(
title = ggplot2::waiver(),
theme = NULL,
nbin = NULL,
display = "raster",
alpha = NA,
draw.ulim = TRUE,
draw.llim = TRUE,
angle = NULL,
position = NULL,
direction = NULL,
reverse = FALSE,
order = 0,
available_aes = c("colour", "color", "fill", "ribbon_fill", "gene_fill",
"feature_fill", "region_fill"),
size_scale = 1,
...
)
guide_ggchord_colorbar(
title = ggplot2::waiver(),
theme = NULL,
nbin = NULL,
display = "raster",
alpha = NA,
draw.ulim = TRUE,
draw.llim = TRUE,
angle = NULL,
position = NULL,
direction = NULL,
reverse = FALSE,
order = 0,
available_aes = c("colour", "color", "fill", "ribbon_fill", "gene_fill",
"feature_fill", "region_fill"),
size_scale = 1,
...
)
Arguments
title |
Guide title. |
theme |
Optional guide-specific theme. |
position, direction |
Guide position and direction. |
override.aes |
A list of legend-key aesthetic overrides. |
nrow, ncol |
Legend key layout. |
reverse |
Whether to reverse the key order. |
order |
Guide order. |
size_scale |
Positive multiplier for keys, spacing and typography. ggchord's automatically generated guides derive this from the active export device; direct calls default to 1. |
... |
Additional arguments passed to the corresponding ggplot2 guide. |
nbin |
Number of colourbar bins. |
display |
Colourbar display method. |
alpha |
Colourbar alpha override. |
draw.ulim, draw.llim |
Whether to draw upper/lower limit ticks. |
angle |
Tick-label angle. |
available_aes |
Aesthetics accepted by the guide. |
Value
A ggplot2 guide object.
Convert explicit homology-cluster membership to feature links
Description
Connects feature intervals belonging to the same declared cluster for explicitly requested sequence pairs. Membership is an input assertion, not an inferred alignment: no identity, alignment length or score is invented. Both sequence and feature identifiers are kept exactly as supplied.
Usage
link_ggchord_clusters(
feature_data,
membership,
pairs,
paralogs = c("drop", "all"),
segment_policy = c("error", "span"),
max_links = 10000
)
Arguments
feature_data |
Feature data frame with |
membership |
Data frame with |
pairs |
Data frame with explicit |
paralogs |
How to handle multiple members per cluster and sequence:
|
segment_policy |
|
max_links |
Positive integer upper limit for generated rows, default 10000. Exceeding it stops before Cartesian products are allocated. |
Details
The default paralogs = "drop" retains only comparisons containing exactly
one member on each side. Ambiguous one-to-many/many-to-many comparisons are
omitted and reported. "all" explicitly requests their Cartesian product.
Its total size is checked against max_links before any links are expanded.
Pair row order and its query/subject roles are retained. Self-pairs and
repeated pairs (including the reversed pair) must be resolved by the caller.
Feature IDs normally identify one row. If repeated rows deliberately
describe one discontinuous feature, segment_policy = "span" requires
one sequence, one strand, and non-overlapping intervals. The link then
anchors the feature's outer genomic bounds; real segments remain in the
qsegments and ssegments list-columns. This span is a feature anchor,
never an exon-to-exon alignment, and does not remove intervening sequence.
Nested segments fields in a single feature row are retained unchanged.
Unknown feature IDs in membership are reported and omitted. Malformed
identifiers, conflicting cluster assignments, ambiguous repeated features,
unsupported origin-crossing intervals and unknown pair sequence IDs stop
with an actionable error. Feature IDs not assigned to a cluster are also
listed in the report. Negative strands reverse their link endpoints;
unknown strands retain increasing coordinates and orientation_known = FALSE.
Value
A list with data, an ordinary link data frame, and report.
Links retain cluster/member IDs, strands, source feature/membership rows
and segment tables. report$comparisons lists member counts, output counts
and retention/omission reasons for each requested pair and clusters
represented on either side (clusters absent from both sides are omitted);
report$members retains membership metadata with resolution status.
report$valid is false when membership contains unknown feature IDs.
See Also
Examples
library(ggchord)
library(dplyr)
data(plasmid_example_pUC19)
data(plasmid_example_pETDuet_1)
homolog_source <- bind_rows(plasmid_example_pUC19, plasmid_example_pETDuet_1)
homolog_seq <- homolog_source |>
select(accver, length)
cluster_features <- homolog_source |>
find_common_features() |>
filter(type == "CDS", anno == "AmpR") |>
select(accver, start, end, strand, anno) |>
arrange(match(accver, homolog_source$accver)) |>
mutate(feature_id = paste(accver, start, end, sep = ":"))
# Membership is computed from exact strand-corrected CDS DNA equality, not gene names.
reverse_complement <- function(sequence) {
bases <- strsplit(sequence, "")[[1]]
chartr("ACGT", "TGCA", paste(rev(bases), collapse = ""))
}
coding_sequences <- cluster_features |>
left_join(select(homolog_source, accver, sequence), by = "accver") |>
rowwise() |>
mutate(
coding_dna = substr(sequence, start, end),
coding_dna = if (strand == "-") reverse_complement(coding_dna) else coding_dna
) |>
ungroup()
cds_dna <- pull(coding_sequences, coding_dna)
membership <- tibble(
feature_id = cluster_features$feature_id,
cluster_id = paste0("exact_CDS_", match(cds_dna, unique(cds_dna)))
)
homologs <- link_ggchord_clusters(cluster_features, membership,
pairs = tibble(qaccver = homolog_seq$accver[1], saccver = homolog_seq$accver[2])
)
loci <- find_ggchord_loci(homolog_seq, cluster_features,
targets = cluster_features$feature_id[cluster_features$anno == "AmpR"][1],
upstream = 100, downstream = 100
)
gene_palette <- c("+" = "#56887C", "-" = "#B58169", "." = "#AAB9AE")
doc_theme <- theme_ggchord_publication(
axis.text = element_text(size = 9), axis.text.check.overlap = TRUE
) +
theme(legend.position = "bottom")
p_homologs <- ggchord(seq_data = homolog_seq) +
geom_link_ribbon(data = homologs$data, fill = "#ADC5B9", alpha = .6) +
geom_seq() +
geom_gene(data = cluster_features) +
geom_seq_label(size = 4) +
coord_collinear() +
scale_gene_fill_manual(values = gene_palette) +
doc_theme
Compose a source region and an explicit local detail plot
Description
Marks real source intervals in registered genomic panels and connects them to the same intervals in independent genomic or registered character details. A detail or source can itself be a nested Fusion. Returns a Fusion, not a new Coord or a crop of an existing image. Ordinary ggsave rebuilds both panels, highlights and leaders at the actual target size.
Usage
magnify_ggchord(
plot,
region,
detail_plot,
side = c("right", "top", "left", "bottom"),
center_size = NULL,
detail_size = NULL,
connector = c("leader", "none", "envelope"),
colour = "#B45309",
alpha = 0.2,
highlight_width = 1.5,
linewidth = 0.35,
linetype = 2,
detail_box = NULL,
allow_overlap = FALSE,
center_box = NULL,
route = c("direct", "avoid"),
guides = c("keep", "collect"),
frame_region = NULL
)
Arguments
plot |
A registered ggchord genomic source plot or nested Fusion. |
region |
Nonempty data frame with |
detail_plot |
An explicit registered ggchord genomic plot, nested Fusion,
a character plot from |
side |
A named side from fusion_panel(), including diagonal sides. For a list of plots, supply a character vector named by panel ID, with distinct fixed sides or repeated auto values for automatic perimeter allocation. Every input region still explicitly selects its detail panel. |
center_size, detail_size |
Optional panel width/height fractions, following
|
connector |
|
colour |
Fixed highlight/leader colour. |
alpha |
Highlight opacity in |
highlight_width |
Positive highlight band width in physical mm. Character panels instead follow the actual cell height. |
linewidth |
Nonnegative leader width using the usual ggplot2 convention. |
linetype |
Leader line type, default dashed. |
detail_box |
Explicit detail allocation instead of side/detail_size, using the box convention in fusion_panel(). For multiple plots, supply a named list covering every detail. Physical boxes are rechecked at target size. |
allow_overlap |
Deliberately permit overlapping containers, following ggchord_fusion(). Later panels cover earlier ones; default FALSE. |
center_box |
Explicit source allocation instead of center_size. |
route |
Direct boundary leaders (default), or avoid to route around measured other containers and native text/guide envelopes. Endpoints stay fixed; no clear route fails rather than hiding the selection. |
guides |
Child legend placement, passed to |
frame_region |
Optional data frame with one row per region, in the same order, containing ordered positive source start/end coordinates. It changes only the source frame and leader departure points; region, detail data and the measured magnification ratio stay unchanged. NULL (default) uses the exact selected interval. Optional accver must match region. Each frame must be visible in the same source instance. Split origin-wrapping frames/selections into explicit intervals before using it. |
Details
Build detail_plot explicitly with focus_ggchord_data() or other documented
source-aware operations. This function does not copy/filter arbitrary layers
or silently choose a local/global Stat policy. The supplied detail plot owns
its data, mappings, statistics and labels. Original source origins, including
renamed/repeated focus windows, are used to resolve the same interval.
Value
A ggchord_fusion() object. export_ggchord_fusion() additionally
returns focus_regions, focus_fronts and leaders in mm, plus original
focus_region_data (without metadata-name collisions), preserving the input
region, exact instances, source origins and sampled physical path-length ratio.
The derived tables use region_row to identify the original input row and
region_piece to identify the origin-split piece. The raw input stays intact.
Stat scope is recorded as explicit_detail_plot. Leaders do not appear in
connections or relationship_data. leader_paths contains the final decorative
polyline vertices. Routing is deterministic in measured physical space, not
a guarantee of globally optimal layout or automatic layer rebuilding. The measured ratio may be below one if the chosen
detail allocation does not enlarge the region.
Envelope leaders use their group's first region_row as the export key;
focus_regions$leader_group records that key for every member selection.
frame_start/frame_end record the displayed source frame independently of
start/end; explicit overrides are retained in focus_frame_region_data.
Examples
library(dplyr)
data(plasmid_example_pUC19)
whole <- ggchord(plasmid_example_pUC19) + geom_seq() + coord_circular()
region <- tibble(accver = "pUC19", start = 101, end = 1900)
local <- focus_ggchord_data(plasmid_example_pUC19, loci = region)
detail <- ggchord(local$seq_data) +
geom_seq() + coord_collinear(seq_axis = "vertical")
magnify_ggchord(whole, region, detail)
magnify_ggchord(whole, region, detail,
center_box = c(.02, .35, .2, .8), detail_box = c(.45, .98, .1, .9),
connector = "envelope")
magnify_ggchord(whole, region, detail,
frame_region = tibble(start = 81, end = 1920))
Map exact alignment columns and source positions
Description
Looks up existing cells within one alignment row. Never interpolates across gaps or discarded columns. Filter an alignment with ordinary data operations before looking up positions to restrict the available window.
Usage
map_alignment_position(data, accver, position, inverse = FALSE)
Arguments
data |
Long alignment frame from |
accver |
One alignment-row ID, even if its |
position |
Numeric positions, positive integral or NA. |
inverse |
FALSE maps alignment columns to source positions; TRUE maps source positions to alignment columns. |
Value
A frame with input_position, accver, alignment_column, source_accver, source_position, is_gap and matched. A known gap column has matched TRUE and source_position NA; an unavailable position has matched FALSE.
Examples
# Explicit synthetic format example.
aligned <- as_ggchord_alignment(c(A = "AC-G", B = "ACTG"), "DNA")
map_alignment_position(aligned, "A", c(2, 3))
map_alignment_position(aligned, "A", 3, inverse = TRUE)
Map native sequence positions and display coordinates
Description
Maps positions for ordinary ggplot2 annotation layers without modifying source tables. Inverse mapping returns the chosen relative or source sequence positions. In a segmented layout, specify the window accession rather than its parent source accession. Positions outside that window, including display gaps, produce an error instead of being extrapolated into omitted sequence.
Usage
map_ggchord_position(
plot,
accver,
position,
inverse = FALSE,
source = FALSE,
axis = NULL
)
Arguments
plot |
A ggchord plot using |
accver |
Sequence identifiers, scalar or one per position. |
position |
Numeric genomic positions, or layout x when |
inverse |
Convert layout x back to native sequence positions. |
source |
Use original source coordinates after focusing. |
axis |
Dotplot axis to map, either |
Value
A data frame with accver, position, x, y and sequence_unit. Dotplots also record the selected axis; the other display coordinate is NA.
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
p <- ggchord(seq_data = seqs) +
geom_seq() +
coord_collinear()
map_ggchord_position(p, seqs$accver[1], position = 100)
Merge adjacent or overlapping alignment blocks of the same sequence pair
Description
Merges alignment blocks that belong to the same (query, subject) pair, are
adjacent (gap <= max_gap) or overlapping on both sequences, and are
compatible. The merged pident is weighted by alignment length. Merging is
deliberately conservative: blocks whose merged query and subject spans would
differ by more than max(max_gap, 1), whose pident differs by more than
min_pident_difference, or whose orientation differs (when
require_same_orientation) are left unmerged.
With the default orientation check, subject bounds must also progress in
the order implied by the relative direction; crossing block orders remain
separate.
Query/subject identifiers always define separate groups, even when
group_by selects additional metadata. An unmerged row retains its
original alignment length. For a merged row, length is the query
envelope span, not a newly computed alignment length; .length_estimated
marks this display summary. Source lengths and identities are retained in
the report. Overlap can count aligned bases more than once in the weighted
identity; gaps can add unaligned bases to the envelope. Use the original
blocks for alignment statistics.
Rows with a single-base endpoint remain independent: endpoint order cannot
define an absolute direction for an aggregate envelope.
Usage
merge_ggchord_ribbons(
ribbon_data,
max_gap = 0,
min_pident_difference = 0,
require_same_orientation = TRUE,
group_by = c("qaccver", "saccver"),
extra_columns = c("consistent", "first")
)
Arguments
ribbon_data |
data.frame in ribbon_data format. |
max_gap |
Numeric, default 0. Maximum gap (in bp) allowed between two blocks on both sequences for them to be merged. |
min_pident_difference |
Numeric, default 0. When > 0, two blocks are only merged when their pident difference is <= this value. |
require_same_orientation |
Logical, default |
group_by |
Character vector, default |
extra_columns |
How to handle columns other than the required ribbon
fields when multiple rows are merged. |
Value
A list with data (merged data frame with source_rows
attribute) and report (data.frame with output_row,
from_rows, n_merged, and list-columns source_length
and source_pident for every output row).
See Also
Examples
library(dplyr)
data(ribbon_data_example)
links <- ribbon_data_example |>
select(qaccver, saccver, qstart, qend, sstart, send, pident, length)
out <- merge_ggchord_ribbons(links, max_gap = 100)
out$report
Optimize sequence order and orientation for ribbon readability
Description
Searches deterministic sequence-order and orientation changes that reduce
weighted ribbon centre-line crossings and long chord spans. It never
modifies the supplied data and never accepts a worse arrangement. Inputs
above 2,000 ribbons use a deterministic 64-bin approximation and record
approximate = TRUE in the returned report.
Usage
optimize_ggchord_layout(
seq_data,
ribbon_data,
seq_order = NULL,
seq_orientation = NULL,
optimize = c("order", "orientation"),
weight = c("length", "count", "pident"),
max_iter = 50L
)
Arguments
seq_data |
Sequence data containing |
ribbon_data |
Alignment data in ggchord ribbon format. |
seq_order |
Optional initial complete sequence order. The default uses
the row order of |
seq_orientation |
Optional initial orientation (1 or -1), scalar, complete vector, or named vector. |
optimize |
Any of |
weight |
Objective weight: |
max_iter |
Positive integer maximum number of improving search rounds. |
Value
An object of class ggchord_layout_optimization containing
seq_order, seq_orientation, before/after scores and a report.
See Also
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
data(ribbon_data_example)
links <- ribbon_data_example |>
select(qaccver, saccver, qstart, qend, sstart, send)
suggestion <- optimize_ggchord_layout(seqs, links, weight = "count")
suggestion$seq_order
Circular plasmid sequence examples
Description
Thirteen one-row data frames generated from every reference FASTA record
under examples/plasmid/. The file stem is used unchanged as both accver
and the display label; the DNA sequence is copied without biological
modification. Feature and restriction annotations are generated at run time
with find_common_features() and find_restriction_sites().
Format
A one-row data frame with accver, display label, length, and
the DNA sequence.
The plasmid_example_pUC19c name is an alias
of plasmid_example_pUC19, including its accver. It must not be confused
with an independently imported GenBank pUC19c record such as L09137.2.
Source
examples/plasmid/.
Stack overlapping genes or features on local lanes
Description
Assigns overlapping intervals on the same sequence and side to radial lanes.
Explicit display priority is ordered first, then intervals by decreasing
length. Every interval takes the nearest collision-free lane; feature type,
name and colour never choose a lane.
The resulting anchors are shared with gene label layers because stacking is
solved before polygons and labels are generated.
In coord_collinear(), these local lanes become parallel horizontal bands;
they do not represent circular physical tracks or radii.
Usage
position_feature_stack(
spacing = 0.1,
side = c("strand", "outside", "inside"),
base_position = NULL
)
Arguments
spacing |
Positive minimum radial distance between adjacent feature lanes. Circular plasmid layout enlarges the first transition into a main label corridor and reserves at least one label track between deeper overlapping feature lanes. |
side |
Legacy track-side selector retained for compatibility when
|
base_position |
Optional identity, strand, or plasmid Position applied before interval-overlap detection and lane allocation. |
Value
A ggplot2 Position object for geom_gene() or geom_feature().
Place both feature strands on one shared band
Description
Place both feature strands on one shared band
Usage
position_plasmid(offset = -0.1)
Arguments
offset |
Signed local-normal offset. Negative values place the shared band inside a circular sequence and positive values place it outside. |
Value
A ggplot2 Position object.
Place features on opposite sides according to strand
Description
Positive signed offsets point away from the plot centre and negative
offsets point inward. A scalar is expanded to + = offset and
- = -offset; explicitly strand-named values are already signed and are
not flipped again.
In coord_collinear(), the positive local normal points upward and the
negative local normal downward, regardless of sequence orientation.
Usage
position_strand(offset = 0.1)
Arguments
offset |
A finite scalar or a flexible per-sequence/per-strand specification. |
Value
A ggplot2 Position object.
Place a quantitative layer in an explicit sequence-local band
Description
Layers with the same track ID share a band and numerical scale across all displayed sequences and windows. Their declarations must agree. Outside means positive local normal (up in linear coordinates), inside negative. The coordinate system resolves physical placement; feature-stack lanes and sequence ring radii are unrelated to track IDs.
Usage
position_track(
track,
side = c("outside", "inside"),
order = 1,
width = grid::unit(4, "mm"),
gap = grid::unit(1, "mm")
)
Arguments
track |
One stable nonempty character ID. |
side |
|
order |
Finite ordering priority, nearest band first. Ties use ID order. |
width, gap |
Positive band width and nonnegative preceding gap. Absolute grid units (mm, cm, inches or points) are resolved against the render context. Numeric values retain native layout units. Numeric per-sequence vectors/lists follow the usual sequence parameter formats. |
Value
A ggplot2 Position object for the three track geoms.
Examples
position_track("depth", width = unit(4, "mm"))
Prepare named ggchord tables with an explicit audit trail
Description
Converts inputs using the existing as_ggchord_*() adapters and returns
named feature/link collections alongside the constructor's three tables.
Collections are passed explicitly to layers, for example
geom_feature(data = result$features$sites); preparation never adds layers.
Import files first with the appropriate reader. No file format, alignment,
sequence length, genome membership or biological identity is guessed.
Usage
prepare_ggchord_data(
seq_data,
ribbon_data = NULL,
gene_data = NULL,
features = list(),
links = list(),
mapping = list(),
steps = list(),
feature_data = NULL
)
Arguments
seq_data |
Sequence input accepted by |
ribbon_data |
Optional paired intervals accepted by |
gene_data |
Optional directional gene input accepted by
|
features, links |
Named lists of feature or paired-interval inputs. |
mapping |
Named list with optional |
steps |
Named list of explicit helper argument lists. Supported names:
|
feature_data |
Unified annotation table, mutually exclusive with gene_data. |
Details
By default this only converts and validates. Optional operations run in the
fixed order clean, filter, deduplicate, merge, bundle, optimize.
Each entry in steps is a named list of arguments for the corresponding
existing helper. An empty list requests its defaults. clean affects only
the constructor tables; the other operations affect ribbon_data only.
Preparation sets cleaning's reversed_interval = "keep" by default to
preserve directional endpoints. Explicit "sort" cannot be followed by
deduplication, merging, bundling or optimization, which use those endpoints.
Those operations also reject previously sorted input whose direction
contradicts the endpoints; supply the original directional link table.
Geometry, named feature/link tables and the original inputs are never
silently filtered, merged or reoriented. Optimization returns a suggestion.
Expensive pairwise duplicate diagnostics are disabled in validation here;
request steps = list(deduplicate = list(...)) to deduplicate explicitly.
An optional genome column in seq_data groups contigs as metadata.
accver must remain globally unique; contigs are never concatenated.
Stable feature IDs and parent ID lists are preserved when supplied, not
manufactured from row numbers. Repeated IDs can describe feature segments;
uniqueness for a specific join is checked by the consumer, such as
find_ggchord_loci().
Value
A list with seq_data, ribbon_data, gene_data, features,
links and report. report$valid describes final validity, with
validation before/after, feature_issues, per-link validations,
conversions, steps, effective step_arguments, a ribbon source_rows list (original input rows
contributing to each output row), pair_counts, and optional
layout_suggestion. Structural conversion errors stop; biological
reference/bounds errors remain in the report and are never repaired by
default. Helper stage reports number rows in that stage's input.
See Also
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
data(ribbon_data_example)
links <- ribbon_data_example |>
select(qaccver, saccver, qstart, qend, sstart, send)
data(gene_data_example)
genes <- gene_data_example |>
transmute(accver, start, end, strand = source_strand)
prepared <- prepare_ggchord_data(seqs, links, features = list(genes = genes))
prepared$report
Inspect the bundled sequencing-primer catalogue
Description
The catalogue stores one searchable record per distinct oligonucleotide.
Set aliases = TRUE to obtain the source rows, including multiple biological
names that share one sequence. The source direction is retained only as a
descriptive hint; binding strand is determined from the target sequence.
Usage
primer_catalog(set = c("all", "universal"), aliases = FALSE)
Arguments
set |
Return all records or only the commonly used universal subset. |
aliases |
Return source alias records instead of the sequence catalogue. |
Value
A data frame.
See Also
Examples
head(primer_catalog("universal"))
head(primer_catalog("universal", aliases = TRUE))
Print a cleaned ggchord data result
Description
Shows the dimensions of the cleaned tables and the first rows of the change report.
Usage
## S3 method for class 'ggchord_clean'
print(x, ...)
Arguments
x |
A |
... |
Ignored. |
Value
The object invisibly.
See Also
Project protein domains or genomic features through a spliced CDS map
Description
Protein input uses one-based inclusive observed-residue coordinates. Genomic
output preserves exon gaps in segments and uses the parent's biological
strand; its outer envelope is not a claim that introns encode the domain.
The inverse projects only intersections with coding bases, reports excluded
bases, and uses the CDS feature ID as its protein coordinate namespace.
This namespace is not an inferred protein accession. Inputs may supply a
genomic segments list-column to describe disjoint genomic pieces.
Usage
project_ggchord_features(
feature_data,
cds,
from = c("protein", "genome"),
codon_boundary = c("error", "expand")
)
Arguments
feature_data |
Domain/feature data frame with |
cds |
A map from |
from |
|
codon_boundary |
Inverse projection policy: |
Details
Each domain retains its explicit feature_id, single CDS parent, source
interval and source row. Source metadata survives with source_ prefixes
on name conflicts. Multiple biological parents must be expanded explicitly
before projection. Unknown parent, intronic-only, out-of-range, reversed,
inconsistent-strand and ambiguous codon-boundary input produce errors.
codon_boundary = "expand" explicitly permits an inverse interval to cover
partial codons and reports this expansion; it does not modify source bases.
Value
Ordinary feature table with projected accver, start, end,
strand, directionality, segments, parent IDs, genetic-code metadata,
source coordinates and a ggchord_projection provenance attribute.
See Also
Examples
library(dplyr)
data(plasmid_example_pUC19)
feature_source <- find_common_features(plasmid_example_pUC19)
features <- feature_source |>
select(accver, start, end, strand, type, anno)
coding <- features |>
filter(anno == "AmpR", type == "CDS") |>
select(accver, start, end, strand) |>
mutate(feature_id = paste(accver, "AmpR", sep = ":"), phase = 0)
cds <- build_ggchord_cds(coding, genetic_code = 11)
# Select residues for display; this is not a detected domain.
selected <- tibble(
feature_id = "selected_residues", parent_id = coding$feature_id,
start = 2, end = 20
)
project_ggchord_features(selected, cds)
Project explicitly ungapped protein links to genomic coding segments
Description
Splits paired protein intervals wherever either CDS crosses a segment
boundary, retaining query/subject roles and genomic endpoint directions.
This is a codon-coordinate correspondence, not a new nucleotide alignment.
Source protein identity and length remain prefixed metadata and are never
emitted as nucleotide pident or alignment length. General gapped
alignments require explicit per-column alignment information and cannot be
projected by this endpoint-only helper.
Usage
project_ggchord_links(link_data, cds, ungapped = FALSE)
Arguments
link_data |
Data frame with |
cds |
A map from |
ungapped |
Must explicitly be |
Value
A paired genomic interval table with CDS parent IDs, source row,
piece number, genomic strands, projected_bases, source-prefixed input
metadata and projection provenance. No alignment identity is computed.
See Also
Examples
library(dplyr)
data(plasmid_example_pUC19)
feature_source <- find_common_features(plasmid_example_pUC19)
features <- feature_source |>
select(accver, start, end, strand, type, anno)
coding <- features |>
filter(anno == "AmpR", type == "CDS") |>
select(accver, start, end, strand) |>
mutate(feature_id = paste(accver, "AmpR", sep = ":"), phase = 0)
cds <- build_ggchord_cds(coding, genetic_code = 11)
# Self-correspondence of one real CDS, solely to demonstrate coordinate conversion.
# The same observed residues are paired, so the correspondence is ungapped.
selected <- tibble(
qfeature_id = coding$feature_id, sfeature_id = coding$feature_id,
qstart = 1, qend = 20, sstart = 1, send = 20
)
project_ggchord_links(selected, cds, ungapped = TRUE)
Six pairwise BLASTp alignments between the example proteins
Description
Observed BLASTp alignments between every unordered pair of the four complete proteins in protein_seq_data_example. The raw all-against-all output retains self hits and both query/subject directions. This teaching table retains one direction per pair, ordered by the sequence table.
Usage
protein_ribbon_data_example
Format
A data frame with six rows containing the twelve standard BLAST
fields, physical .source_line provenance and sequence_unit = "aa".
Endpoints are one-based inclusive amino-acid positions.
Source
examples/protein/all-vs-all-blastp.tsv, generated with NCBI
BLASTp 2.17.0+ from unchanged complete protein records. The command,
source hashes and sequence selection are recorded in
examples/protein/sources.json.
See Also
protein_seq_data_example, geom_link_ribbon
Four complete protein sequences for comparison
Description
Three EMALE proteins and one Mavirus protein selected from public complete FASTA records. Their six pairwise comparisons are in protein_ribbon_data_example. Lengths describe complete proteins.
Usage
protein_seq_data_example
Format
A data frame with four rows and columns:
- accver
Unchanged protein identifier.
- length
Full length in amino acids.
- sequence_unit
The declared coordinate unit,
"aa".- sequence
Complete protein residues retained from the source FASTA.
Source
Public EMALE/Mavirus FASTA records. Selection, source hashes,
BLASTp version and arguments are in examples/protein/sources.json.
Rebuild with data-raw/prepare-bundled-proteins.py and
data-raw/generate_protein_data.R.
See Also
protein_ribbon_data_example, ggchord
Read aligned FASTA with source-to-column mapping
Description
Reads one alignment file. Whitespace wrapping is removed by the FASTA reader; gaps and case remain unchanged. Records must have equal width. Does not run an aligner or infer strand, genomic origins, mismatch classes or CDS phase.
Usage
read_aligned_fasta(
file,
alphabet,
source_data = NULL,
source_file = FALSE,
circular = FALSE
)
Arguments
file |
A single local aligned FASTA path; no multi-alignment concatenation. |
alphabet |
Explicit |
source_data |
Optional data frame with one row per alignment |
source_file |
Logical. Also retain |
circular |
Explicit logical declaration that every source is circular, default FALSE. Requires source_data with full source_length or full sequence. Coordinates wrap at that length in the declared strand direction; nongap characters may cover at most one complete tour. Adds source_circular and source_length columns. A circular plot never activates this conversion. |
Value
The long frame from as_ggchord_alignment(), with the physical FASTA
header .source_line, optional .source_file, and import provenance.
See Also
geom_residue(), map_alignment_position()
Examples
## Not run:
# Requires the source checkout or tutorial input bundle.
dna <- read_aligned_fasta("examples/alignment/opuntia-aligned.fasta", "DNA")
## End(Not run)
Read BED intervals as ggchord features
Description
Reads standard BED3 through BED12. Starts are converted from zero-based half-open intervals to one-based inclusive intervals; accession identifiers are kept verbatim. Blank lines, comments, and custom-track header lines are skipped. Every data row in a file must have the same number of fields. Zero-width insertion records cannot be represented as nonempty genomic intervals and produce an explicit error.
Usage
read_bed(file = NULL, files = NULL, source_file = FALSE)
Arguments
file |
Optional path vector or glob patterns; read before |
files |
Optional paths or wildcard patterns for multiple BED files. |
source_file |
Logical. Add a |
Details
BED names are labels, not guaranteed unique feature IDs. Unspecified strand
remains "." and directionality = "none"; use geom_feature() for these
records. Optional fields retain their BED names and coordinate conventions,
including zero-based thickStart, thickEnd, and relative blockStarts.
BED12 additionally creates a segments list-column of one-based inclusive
block intervals after checking block counts, boundaries and non-overlap.
Blocks are retained in genomic order on both strands. No colour or shape is
inferred from BED display fields. BED extensions beyond column 12 require an
explicit data-frame conversion with as_ggchord_feature().
Value
A feature data frame with accver, start, end, strand,
directionality, original chromStart/chromEnd, optional BED fields,
and .source_line (the physical file line). A ggchord_import attribute
records the input/output coordinate conventions and files.
See Also
https://genome.ucsc.edu/FAQ/FAQformat.html#format1
Examples
library(dplyr)
data(plasmid_example_pUC19)
feature_source <- find_common_features(plasmid_example_pUC19)
features <- feature_source |>
select(accver, start, end, strand, type, anno)
bed <- tempfile(fileext = ".bed")
bed_rows <- features |>
transmute(accver, start0 = start - 1L, end)
write.table(bed_rows, bed,
sep = "\t", quote = FALSE, row.names = FALSE, col.names = FALSE
)
read_bed(bed)
unlink(bed)
Read bedGraph intervals as quantitative track data
Description
Reads four columns, converts zero-based half-open coordinates to one-based inclusive positions, and retains every finite signed value and source row. Missing intervals remain absent: no zero filling, interpolation, sorting or aggregation is performed. Overlapping rows are retained as observations, not silently resolved into a single value. Choose any summarisation explicitly.
Usage
read_bedgraph(file = NULL, files = NULL, source_file = FALSE)
Arguments
file |
Optional input path vector or glob patterns, before files. |
files |
Optional additional paths or wildcard patterns for bedGraph files. |
source_file |
Logical. Add .source_file to each row, default FALSE. |
Details
A file contains one signal. More than one track definition is rejected; split different browser tracks explicitly rather than mixing their domains. Comments and display headers are retained in import provenance. Their colour, smoothing and other display instructions never configure a ggchord plot. Sequence identifiers, including literal track/browser, are retained verbatim. Neither value units nor sequencing coverage are inferred from the file name.
Value
A data frame with accver, start, end, value, original chromStart, chromEnd, dataValue and physical .source_line. The ggchord_import attribute records conventions, per-file row counts, and unchanged headers. When combining different signals, keep source_file = TRUE and select each signal's layers/scales explicitly. Coordinate units follow source metadata.
See Also
geom_track(), scale_track_value_continuous()
Examples
# Actual 100-bp-window GC percentages; not measured read coverage.
path <- system.file("extdata", "pUC19-gc-100.bedGraph", package = "ggchord")
signal <- read_bedgraph(path)
head(signal)
Read paired BED intervals as ggchord links
Description
Reads tab-separated BEDPE with six required columns, optional name, score, strand1 and strand2 in standard order, and any additional fields. Each file must have a consistent field count. Blank/comment lines and tab-free track/browser headers are skipped. Accession identifiers and the order of the two anchors are retained: the first anchor is query, the second subject.
Usage
read_bedpe(
file = NULL,
files = NULL,
source_file = FALSE,
unmapped = c("error", "keep")
)
Arguments
file |
Optional local path vector or glob patterns; read before |
files |
Optional additional local paths or glob patterns. |
source_file |
Logical. Add a |
unmapped |
|
Details
Zero-based half-open intervals become one-based inclusive intervals.
Negative-strand anchor endpoints decrease, matching as_ggchord_link() for
paired interval objects. Unspecified strands remain "."; relative anchor
direction is known only when both anchors and both strands are known.
Anchor direction does not establish a pairwise alignment. No identity,
alignment length, read support or full sequence length is inferred.
Original standard fields are retained as character columns, including
arbitrary score strings. Extra fields are retained in the bedpe_extra
list-column as character vectors named by their physical column number.
Names are labels, not guaranteed unique HSP IDs. Unknown chromosome "."
and coordinate -1 are explicit missing-value sentinels. The default stops
on incomplete anchors; unmapped = "keep" retains them for auditing with
missing canonical fields and q_mapped/s_mapped flags. Filter for both
flags before adaptation or plotting. Invalid known coordinates, including
zero-width intervals, are always errors.
Value
A data frame with canonical q/s endpoints, anchor strands, mapping
flags, relative direction, original BEDPE fields, bedpe_extra and physical
.source_line. The ggchord_import attribute records files, row counts
and coordinate conventions. The keep policy does not make missing anchors
drawable and does not manufacture source positions.
See Also
as_ggchord_link(), ggchord_data_contract,
https://bedtools.readthedocs.io/en/latest/content/general-usage.html#bedpe-format
Examples
library(dplyr)
data(ribbon_data_example)
# Re-encode observed intervals for a format round trip, not paired-read evidence.
paired <- ribbon_data_example |>
transmute(
chrom1 = qaccver, start1 = pmin(qstart, qend) - 1, end1 = pmax(qstart, qend),
chrom2 = saccver, start2 = pmin(sstart, send) - 1, end2 = pmax(sstart, send)
)
path <- tempfile(fileext = ".bedpe")
write.table(paired, path,
sep = "\t", quote = FALSE, row.names = FALSE, col.names = FALSE
)
read_bedpe(path)
unlink(path)
Read indexed BigWig signals through an optional mature decoder
Description
Uses optional rtracklayer and its GRanges import. Those coordinates are already one-based inclusive and are not shifted again. Stored sequence lengths come from the file header, not the last nonmissing interval. Scores retain the binary file's floating-point representation. They are signal values, not original observation counts, identity or read support.
Usage
read_bigwig(file = NULL, files = NULL, which = NULL, source_file = FALSE)
Arguments
file |
Optional local input path vector or glob patterns, before files. |
files |
Optional additional paths or wildcards for local BigWig files. |
which |
NULL for the whole file, or a GRanges / data frame with character accver and numeric start/end in one-based inclusive coordinates. Unknown accessions and out-of-bounds intervals fail explicitly. An empty selection returns no signal rows. The same selection applies to each file. |
source_file |
Logical. Add .source_file to each row, default FALSE. |
Details
Optional selection is an unstranded coordinate union, so overlapping query windows do not duplicate a source signal. Returned runs are clipped to that union. The original query and effective union are retained separately; no pre-clipping window boundaries are invented. Missing ranges stay absent, and imported missing scores remain missing. No zero filling, smoothing, summarisation or value-unit inference is performed. The optional decoder does not support BigWig on Windows; use an existing bedGraph file with read_bedgraph() there instead.
Value
A data frame with accver, start, end, value and original imported score. Import provenance includes decoder/version, each file's sequence dictionary, original query and effective selected intervals. No physical source lines or original measurement IDs are manufactured from a binary file.
See Also
Examples
# Optional Bioconductor decoder loading can take several seconds.
if (.Platform$OS.type != "windows" && requireNamespace("rtracklayer", quietly = TRUE)) {
# Packaged real GC signal, not measured read coverage.
path <- system.file("extdata", "pUC19-gc-100.bw", package = "ggchord")
signal <- read_bigwig(path,
which = data.frame(accver = "pUC19", start = 50, end = 150))
head(signal)
}
Read one or more BLAST tabular output files into ribbon_data format
Description
Both file and files accept literal path vectors or wildcard patterns.
Repeated resolved paths are read once, in first-occurrence order.
Standard -outfmt 6 and -outfmt 7 use the default 12 tabular fields.
Omitting -outfmt
entirely produces pairwise text, which this tabular reader does not parse.
Usage
read_blast(
file = NULL,
files = NULL,
format = c("auto", "outfmt6", "outfmt7", "custom"),
col_names = NULL,
comment = "#",
source_file = FALSE,
...
)
Arguments
file |
Optional path vector or glob patterns; read before |
files |
Optional character vector of BLAST tabular output files (literal paths and/or wildcard patterns). All matched files are read and combined into one data.frame. |
format |
Character. |
col_names |
Optional character vector naming the columns in the file,
used with |
comment |
Character comment character, default |
source_file |
Logical. Add a |
... |
Additional arguments passed to |
Details
The reader also parses BLASTp tabular output. It preserves the producer's
numeric endpoints and does not infer or convert amino-acid/nucleotide units.
Supply complete protein lengths with sequence_unit = "aa" for native
protein plots. Protein intervals require an explicit CDS projection for
plotting on a nucleotide genome. Reading a protein HSP does not establish
an ungapped nucleotide correspondence.
See project_ggchord_features() and project_ggchord_links().
Value
A data.frame with the required ribbon columns first
(qaccver, saccver, qstart, qend, sstart, send) followed by any preserved optional columns.
A ggchord_import attribute records files, per-file output row counts and
the one-based inclusive coordinate convention.
See Also
Examples
## Not run:
library(dplyr)
# Standard 12-column records; requires the source checkout or tutorial input bundle.
source <- read_blast("examples/blastn-standard/MT108731.1__MT118296.1.tsv")
links <- source |>
select(qaccver, saccver, qstart, qend, sstart, send)
## End(Not run)
Read chain alignment blocks without inventing sequence characters
Description
Optional Biopython Bio.Align parses chain coordinates. Each block aligned on both sides becomes one directional interval pair; intervening gaps stay in the source coordinate matrix rather than becoming a false uninterrupted match. Source chain scores and IDs remain in report metadata; neither is an Identity or read-support count. Chain contains no aligned characters.
Usage
read_chain(
file = NULL,
files = NULL,
query_ids = NULL,
subject_ids = NULL,
sequence_unit = c("bp", "aa"),
python = "python3",
source_file = FALSE
)
Arguments
file |
Optional local path vector or glob patterns, before files. |
files |
Optional additional chain paths or patterns. |
query_ids, subject_ids |
Optional named character vectors mapping original query/target IDs to explicit source IDs. Unspecified IDs stay unchanged. Unknown map keys and conflicting full lengths fail. |
sequence_unit |
Declared coordinate unit, "bp" (default) or "aa". The format itself cannot establish the biological unit. |
python |
Existing interpreter with optional Biopython, default "python3". |
source_file |
Add .source_file to ribbon rows, default FALSE. |
Details
The chain query becomes qaccver and its target becomes saccver. Original IDs stay in q_source_accver/s_source_accver. If both assemblies use the same IDs, supply explicit query_ids/subject_ids rather than implicitly merging distinct molecules or auto-prefixing them. Shared final IDs require explicit declaration on both sides and consistent full lengths. This is data identity mapping, not automatic homology discovery or display-instance creation.
Value
A list with seq_data, ribbon_data and report containing original text, chain scores/IDs, full lengths and exact zero-based boundary matrices. Each link retains source_block and source_segment provenance; no source HSP ID, pident, base mismatch script or character alignment is fabricated.
See Also
read_maf(), geom_link_ribbon()
Examples
## Not run:
# Requires an existing Python environment with optional Biopython.
chains <- read_chain("examples/genome-alignments/dna_rna.chain")
head(chains$ribbon_data)
## End(Not run)
Read existing delta alignments through an optional command-line decoder
Description
Invokes an existing show-coords executable with fixed -THld arguments to read NUCMER/PROMER delta. No alignment, filtering, sorting, merging or missing-character reconstruction is performed. Source FASTA paths in the delta preamble are retained as metadata, never opened or downloaded.
Usage
read_delta(
file = NULL,
files = NULL,
executable = "show-coords",
query_ids = NULL,
subject_ids = NULL,
source_file = FALSE
)
Arguments
file |
Optional local path vector or glob patterns, before files. |
files |
Optional additional delta paths or patterns. |
executable |
Existing show-coords executable name or path, default "show-coords". It must already be installed; no environment is modified. |
query_ids, subject_ids |
Optional explicit named source-ID maps,
following |
source_file |
Add .source_file to ribbon rows, default FALSE. |
Details
Query becomes qaccver and reference becomes saccver. Original one-based inclusive directional endpoints and full lengths are checked against the tool output without shifting or inferring lengths. Original numeric-looking IDs stay strings. Source errors and signed delta scripts (including terminal zero) remain attached to each row, with physical alignment/header lines. No sequence characters are reconstructed from these scripts alone.
pident is the decoder's reported percent identity, with its printed precision; it is not inferred from endpoints. For NUCMER this describes nucleotide alignment; for PROMER it describes amino-acid alignment, while endpoint and full-length coordinates still use bp. Similarity, stop percentages and frames remain separate native fields. qspan/sspan are source interval widths, not alignment-column counts. No BLAST length or read-support field is invented.
Value
A list with seq_data, ribbon_data and report. The report retains original text/headers, native decoder output/messages, executable and exact arguments. No executable version is guessed when the tool cannot report one; record the prepared environment's version separately. All source rows remain distinct; no source HSP IDs or observation counts are manufactured. Parsing is explicit data preparation, never a draw-time step.
See Also
read_chain(), read_maf(), geom_link_ribbon()
Examples
## Not run:
# Requires an existing show-coords executable and the source input bundle.
observed <- read_delta("examples/genome-alignments/arabidopsis-first-pair.delta")
head(observed$ribbon_data)
## End(Not run)
Read one or more FASTA files into seq_data format
Description
file reads a single FASTA file; files reads multiple files at once and
combines them. files accepts a character vector of literal paths and/or
wildcard patterns (e.g. "examples/fasta/*.fna").
Usage
read_fasta_lengths(
file = NULL,
files = NULL,
header_delim = NULL,
source_file = FALSE,
sequence_unit = NULL,
keep_sequence = FALSE
)
Arguments
file |
Optional path vector or glob patterns; read before |
files |
Optional character vector of FASTA files (literal paths and/or wildcard patterns). All matched files are read and combined. |
header_delim |
Optional character. When given, each header is split at every occurrence of this delimiter and only the first piece is kept. |
source_file |
Logical. Add a |
sequence_unit |
Optional |
keep_sequence |
Logical, default |
Value
A data.frame with columns accver and length, plus
sequence_unit and sequence when explicitly requested.
A ggchord_import attribute records files and per-file output row counts.
See Also
Examples
## Not run:
library(dplyr)
# Requires the source checkout or tutorial input bundle.
source <- read_fasta_lengths("examples/fasta/MT108731.1.fna")
seqs <- source |>
select(accver, length)
characters <- read_fasta_lengths(
"examples/fasta/MT108731.1.fna", keep_sequence = TRUE
)
## End(Not run)
Read precomputed feature pairs or group memberships
Description
Reads local whitespace-separated pairs (two IDs and an optional opaque score), named groups (group ID followed by members), or unnamed groups (members only). Schemas are explicit; headers are not guessed. Blank lines and whole-line # comments are skipped. IDs, native score strings, physical lines, member order, duplicates and original fields remain traceable. Numeric-looking IDs remain strings. Group indices are local to each file; unnamed groups have no invented biological group ID. Membership never generates pairwise links or asserts orthology.
Usage
read_feature_relations(
file = NULL,
files = NULL,
format = c("pairs", "named_groups", "groups"),
feature_data = NULL,
unmatched = c("error", "report"),
source_file = FALSE
)
Arguments
file |
Optional local paths or patterns, read before files. |
files |
Optional additional local paths or patterns. |
format |
Explicit schema: "pairs" (default), "named_groups", or "groups". |
feature_data |
Optional data frame with unique character feature_id, character accver and numeric start/end in declared source coordinates. Original columns remain in report$feature_data; optional strand is retained. |
unmatched |
"error" (default) rejects IDs absent from supplied feature_data; "report" retains incomplete rows with mapping flags and reports each missing ID. Without feature_data all rows stay unplaced. |
source_file |
Add .source_file to pairs, membership and mapped links. |
Details
Optional feature_data matches unique feature_id values exactly, without editing case, prefixes or versions or guessing gene/CDS parentage. Supply ascending 1-based-inclusive contiguous source intervals, with optional strand (+, - or .). Negative feature strand stays annotation metadata: paired anchor endpoints remain ascending and direction stays missing. These are feature relationships, not basewise alignments. Segmented features require an explicit contiguous anchor table rather than silently using their bounding spans. No full sequence length, identity, support, alignment direction or source characters are inferred.
Value
A list with pairs, membership, ribbon_data (only complete mapped original pairs), and report. Group input returns no pair links. Mapped members carry source intervals in membership. report retains raw files, original fields, missing IDs, unplaced pairs and supplied feature_data. No seq_data is generated from annotation endpoints. File-local record indices must be interpreted with .source_input, not as biological IDs.
See Also
geom_feature(), geom_link_line(), read_gff3()
Examples
path <- system.file("extdata", "plant-feature-groups.txt", package = "ggchord")
relations <- read_feature_relations(path, format = "named_groups")
relations$membership[c("group_id", "feature_id")]
Import local GenBank or GBFF records using an optional mature parser
Description
Uses the public Bio.SeqIO.parse(..., "genbank") API in an explicitly
selected Python environment with Biopython installed. The R package
jsonlite exchanges structured temporary JSON with that process. This
function never installs packages, downloads records, or runs during plot
building. It reads all selected records into memory and is intended for
small to moderate local annotation files, not chromosome-scale streaming.
Usage
read_genbank(
file = NULL,
files = NULL,
feature_types = NULL,
lengths = NULL,
python = "python3",
unsupported = c("error", "report"),
source_file = FALSE
)
Arguments
file |
Optional path vector or glob patterns; read before |
files |
Optional paths or wildcard patterns for several files. |
feature_types |
Optional feature types to select. |
lengths |
Optional named numeric vector of known full sequence lengths,
following |
python |
Interpreter name or path, default |
unsupported |
|
source_file |
Add |
Details
Record IDs, including accession versions, are retained exactly as returned
by the source parser. Full parsed record annotations, feature qualifiers,
source locations, and original file text are retained in report. Feature
IDs use explicit ID, then protein_id for CDS, then locus_tag, then a
non-placeholder parser feature ID. Missing IDs remain missing. Shared
locus_tag values do not invent gene/CDS parent relationships; explicit
Parent qualifiers become parent_ids.
Simple and joined local locations retain one-based inclusive segments
in parser order. Before/after fuzzy bounds retain their source descriptors
and partial flags; they are displayed at the reported boundary rather than
treated as exact biology. Remote locations, missing or unsupported fuzzy
positions, zero-width sites, and mixed-strand joined features are never
flattened into guessed intervals. unsupported = "error" stops by default;
"report" retains these features in report$unplaced_features instead.
An absent ORIGIN sequence does not imply an unknown declared length.
Truly missing/zero lengths require explicit lengths; feature endpoints
are never used to infer full lengths. Protein records require an explicit
protein-coordinate workflow instead of this nucleotide reader.
Value
A list with seq_data, named features$annotation, and report.
Tables can be supplied to prepare_ggchord_data(). Feature rows include
feature_id, parent_ids, segments, source record/feature indices,
qualifiers, source_location, partial_start/partial_end, and
location_operator. report$records retains the complete parsed source
CDS rows also expose source codon_start, genetic_code, biological
partial5/partial3, and translation_exception qualifiers for explicit
downstream coding-coordinate models. Missing CDS codon_start uses the
INSDC default 1, marked by codon_start_source = "format-default".
Bound-only flags remain in bound_partial5/bound_partial3; CDS partial
flags also record initial codon offset or terminal coding remainder, with
their evidence in partial5_source/partial3_source. They describe the
observed coding extent, not proof of a complete biological protein.
No per-segment phase values are invented. segment_order preserves the
source's declared coding-piece order independently of segment_index.
metadata, raw_files retains original text, and unplaced_features
identifies every selected feature not placed under "report".
See Also
https://biopython.org/docs/latest/api/Bio.SeqIO.html
Examples
## Not run:
# Requires the source checkout or tutorial input bundle and optional Biopython.
imported <- read_genbank("examples/format-inputs/pUC19c-L09137.2.gb")
imported$report
## End(Not run)
Read one or more GFF3 files into gene_data format
Description
file reads a single GFF3 file; files reads multiple files at once and
combines them. files accepts a character vector of literal paths and/or
wildcard patterns (e.g. "examples/gff3/*.gff3").
Usage
read_gff3(
file = NULL,
files = NULL,
feature_types = "CDS",
anno_from = c("product", "Name", "gene", "ID"),
unstranded = c("plus", "drop", "keep"),
source_file = FALSE
)
Arguments
file |
Optional path vector or glob patterns; read before |
files |
Optional character vector of GFF3 files (literal paths and/or wildcard patterns). All matched files are read and combined. |
feature_types |
Character vector of feature types to keep, default
|
anno_from |
Character vector of GFF3 attribute keys, tried in order to
fill the |
unstranded |
|
source_file |
Logical. Add a |
Value
A data.frame with accver, start, end, strand, anno
followed by type, source, score, phase, attributes,
source_strand, feature_id (decoded GFF3 ID, or missing) and a
parent_ids list-column. Repeated IDs for discontinuous features and
multiple parents are retained; selecting feature types may omit parents.
A ggchord_import attribute records files, per-file output row counts and
the one-based inclusive coordinate convention.
See Also
Examples
## Not run:
library(dplyr)
# Requires the source checkout or tutorial input bundle.
source <- read_gff3("examples/gff3/MT108731.1.gff3", unstranded = "keep")
features <- source |>
select(accver, start, end, strand, anno)
## End(Not run)
Read existing MAF blocks with exact source characters
Description
Optional Biopython Bio.Align parses local MAF through an explicitly selected Python environment. No alignment is computed. Full source IDs, lengths, block scores, coordinate matrices and original text remain traceable. Empty components and quality/context lines remain in source text/parser metadata; no characters or relations are invented for absent components. Zero-length s components are listed in report$unplaced_components. They do not acquire source positions or links; an empty first anchor is not replaced by another component implicitly.
Usage
read_maf(
file = NULL,
files = NULL,
alphabet = "DNA",
python = "python3",
source_file = FALSE
)
Arguments
file |
Optional local path vector or glob patterns, before files. |
files |
Optional additional MAF paths or patterns. |
alphabet |
Declared DNA, RNA or AA alphabet, default "DNA". |
python |
Existing interpreter with optional Biopython, default "python3". |
source_file |
Add .source_file to alignment/ribbon rows, default FALSE. |
Details
Each block's first component is the query anchor, paired with every other nonempty component. No all-pairs clique or Identity is inferred. Source positions come from the decoder's forward zero-based boundary matrix and are converted once to directional one-based inclusive endpoints. Negative rows decrease from their true forward source coordinate, not the offset on the reverse-complement string. Blocks and input files are separate contexts.
Alignment cells reuse as_ggchord_alignment(). Original symbols and gaps
are retained; gaps have missing source positions. Full lengths do not verify
source characters independently, so source_verified stays FALSE. Filter
.source_input and source_block before column lookup or drawing a character
panel: alignment columns restart at one in each block. No blocks are joined,
renumbered or promoted to complete source sequences.
Value
A list with seq_data (declared full lengths), ribbon_data, alignment cells and report. Source indices and original decoder metadata remain in the report. No pident or read support is manufactured.
See Also
read_chain(), map_alignment_position()
Examples
## Not run:
# Requires an existing Python environment with optional Biopython.
blocks <- read_maf("examples/genome-alignments/ucsc_mm9_chr10.maf")
local <- blocks$alignment[blocks$alignment$source_block == 1, ]
## End(Not run)
Read PAF mappings as ggchord links
Description
Converts zero-based half-open PAF query/target intervals to one-based
inclusive endpoints. Query endpoints increase; target endpoints decrease
for relative strand "-". This display convention preserves relative
orientation and does not infer a biological strand for either sequence.
Usage
read_paf(file = NULL, files = NULL, source_file = FALSE)
Arguments
file |
Optional path vector or glob patterns; read before |
files |
Optional paths or wildcard patterns for multiple PAF files. |
source_file |
Logical. Add a |
Details
length is the reported alignment block length, including gaps, and
pident is 100 * nmatch / length using the reported PAF fields. Both
counts may be approximate when the producer did not compute an alignment.
The importer does not recompute an alignment, validate a CIGAR, or claim
exact base identity. pident_basis records this ratio's provenance.
Mapping quality 255 means unavailable: mapq becomes NA, while
source_mapq retains the original value. Optional typed tags are retained
verbatim in the tags list-column, including unknown tags and their order.
Value
A link data frame with canonical endpoints, qlen, slen,
nmatch, length, pident, mapq, relative orientation, original
zero-based coordinates, tags and .source_line. The ggchord_import
attribute records input/output coordinate conventions and files.
See Also
https://github.com/lh3/miniasm/blob/master/PAF.md
Examples
## Not run:
library(dplyr)
# Requires the source checkout or tutorial input bundle.
links <- read_paf("examples/format-inputs/emales-pair.paf")
links |>
select(qaccver, saccver, qstart, qend, sstart, send)
## End(Not run)
Read existing protein signature matches as AA features
Description
Reads local signature TSV or cached entry JSON from InterPro/Pfam without running an annotation engine or retrieving online data. Accession case and versions remain verbatim, including lowercase accessions returned by the API. Declared full protein lengths supply seq_data; feature endpoints never stand in for full lengths. No source characters or verification are invented.
Usage
read_signature_matches(
file = NULL,
files = NULL,
format = c("scan_tsv", "entry_json"),
source_file = FALSE
)
Arguments
file |
Optional local path vector or glob patterns, before files. |
files |
Optional additional input paths or patterns. |
format |
Explicit schema: "scan_tsv" (default, 11-15 columns) or "entry_json" (cached entry results with metadata/proteins/locations). JSON requires optional jsonlite. No pagination links are followed; declared counts and remaining-page links stay in the report. |
source_file |
Add .source_file to feature rows, default FALSE. |
Details
Source score is a list-column preserving each native scalar/string/missing value. Member-library scores and e-values cannot be assumed comparable; no universal confidence, evalue, Identity or read support is manufactured. Original TSV fields and JSON objects remain in the report. TSV field 10, dates, optional integrated/GO/pathway metadata are retained without guessing version-specific semantics or promoting them to plotting instructions.
Each JSON location remains one feature row, reusing the existing segments contract for actual fragments and their original indices/status. start/end bound that location; gaps between its segments are not filled. Per-file .source_match and entry/protein/location indices retain the source context. Model and signature IDs are labels, not unique feature-instance IDs; feature_id stays missing. All representative and nonrepresentative matches remain. TSV rows retain their original interval and physical line. No grouping across TSV rows is guessed. Match indices need .source_input when several files are combined; none is an invented biological observation ID.
Value
A list with seq_data (aa), features$signature and report. Source lengths, native metadata, raw files and pagination remain traceable. Known length or declared MD5 conflicts for the same accession fail, rather than silently merging different sources. A declared MD5 is retained, not independently verified without actual source characters.
See Also
geom_feature(), geom_feature_label_repel()
Examples
# Explicit re-encoding of cached AA annotations, not a new analysis run.
path <- system.file("extdata", "P00517-signatures.tsv", package = "ggchord")
matches <- read_signature_matches(path)
matches$features$signature[c("accver", "start", "end", "signature_id")]
Read VCF or BCF with optional mature variant decoders
Description
VariantAnnotation reads local VCF text (including gzip). Files ending in .bcf or .bcf.gz first use pysam/HTSlib in the explicitly selected Python environment to transcode to temporary VCF. No parser is installed or run at plot time. This is an in-memory adapter for selected local files, not an indexed chromosome-scale query or variant caller.
Usage
read_vcf(
file = NULL,
files = NULL,
structural = FALSE,
python = "python3",
source_file = FALSE
)
Arguments
file |
Optional local path vector or glob patterns, before files. |
files |
Optional additional VCF/BCF paths or patterns. |
structural |
Logical. Explicitly request optional structural decoding, default FALSE. Duplicate record IDs fail in this mode because mates would be ambiguous. All source records remain accessible in the default mode. |
python |
Existing interpreter with optional pysam for BCF only. Ignored for VCF text; default "python3". No environment is modified. |
source_file |
Add .source_file to returned table rows, default FALSE. |
Details
Each placed source record remains one row, including multiallelic records. Variant
features show the reference allele span at POS, including its padding base;
they are not claimed to be the inserted sequence or a symbolic SV footprint.
Original IDs, REF, ALT lists, QUAL, FILTER, INFO and sample/genotype arrays
are retained. Missing IDs stay missing. No alleles or samples are combined,
filtered, phased or normalised. No support, Identity or full lengths are
inferred from positions. Header length entries that are missing remain NA.
Telomeric or out-of-bounds reference spans remain in the complete parsed
source and report$records[[i]]$unplaced_features rather than being clipped
into invented reference features. Empty VCFs return empty feature tables.
Explicit structural decoding uses optional StructuralVariantAnnotation, with missing-mate inference disabled and positional uncertainty retained. Each reciprocal decoded pair produces one link, with both source record indices; single and unpaired records remain in the source/report. Breakend orientation describes derivative sequence, not homology or feature strand. Links retain ascending confidence intervals and separate orientation fields; no pident, relative Orientation or connection to an absent mate is invented. Decoder-derived metadata is labelled separately from original evidence. Breakends outside known bounds have .plottable = FALSE; affected pairs stay in the report's unplaced_links instead of being clipped to exact boundaries.
Value
A list with features$variant (reference allele spans), breakends, links and report. The report retains each complete parsed VCF object, source record text, original headers/IDs, decoder versions, warnings and sequence dictionaries with unknown lengths preserved. Original INFO and genotype evidence stays in report$records; no caller-specific support field is silently promoted to a universal count. Table .source_input and .source_record refer to the report file and its record order, never an invented biological observation ID. BCF text is decoder output rather than original binary bytes; no physical BCF line numbers are assigned.
See Also
geom_feature(), geom_link_ribbon(), read_bedpe()
Examples
# Optional Bioconductor decoder loading can take several seconds.
if (requireNamespace("VariantAnnotation", quietly = TRUE)) {
path <- system.file("extdata", "chr22.vcf.gz", package = "VariantAnnotation")
# Preserve the original headers and first three observed records.
con <- gzfile(path, "rt")
lines <- character()
records <- 0L
while (records < 3L) {
line <- readLines(con, n = 1L)
if (!length(line)) break
lines <- c(lines, line)
if (!startsWith(line, "#")) records <- records + 1L
}
close(con)
input <- tempfile(fileext = ".vcf")
writeLines(lines, input)
variants <- read_vcf(input)
print(variants$features$variant[c("accver", "start", "end", "feature_id")])
unlink(input)
}
Register an independent character plot for genomic composition
Description
Attaches an explicit source/column map to an ordinary Cartesian ggplot. It remains editable and independently printable. Fusion and magnify rebuild the plot at its final physical size, check registered cells against actual geom_residue positions/labels, and project exact source boundaries. No HSP interpolation or implicit alignment is performed.
Usage
register_ggchord_alignment(plot, data)
Arguments
plot |
A single-panel Cartesian ggplot with geom_residue layers mapping x = alignment_column, y = accver, label = symbol. Identity/reverse x scales and a discrete y scale are supported. Additional independent annotations are allowed. Facets, nonlinear scales, flipped coordinates and position adjustments moving registered cells are rejected. geom_residue(line_width = ...) is supported. Each selected source interval must lie within one displayed line; split cross-line selections explicitly. |
data |
The displayed rows of |
Value
The ordinary plot with a source registration. Use it as detail_plot
in magnify_ggchord() or as an outer fusion_panel(). Region detail_instance
selects an exact alignment row accver when several rows share a source.
Registrations assert supplied provenance; source_verified is not an
independent biological validation. Exported source layouts retain data.
Examples
# Explicit synthetic format example.
cells <- as_ggchord_alignment(c(A = "AC-G", B = "ACTG"), "DNA")
p <- ggplot2::ggplot(cells, aes(alignment_column, accver, label = symbol)) +
geom_residue(aes(fill = symbol), show.legend = FALSE)
register_ggchord_alignment(p, cells)
Restriction sites for the minimal single-genome fixture
Description
Restriction sites for the minimal single-genome fixture
Format
A data frame returned by find_restriction_sites().
Source
Generated from examples/single-genome/minimal.fasta by
data-raw/generate_example_data.R.
Example alignment data
Description
A compact alignment fixture generated deterministically from the BLAST
files under examples/blastn. Alignments shorter than 300 bases are
omitted, and dense sequence pairs retain at most three spatially distributed
representatives so the default chord remains readable. Sparse pairs are
preserved unchanged.
Usage
ribbon_data_example
Format
A data frame containing standard alignment columns (qaccver, saccver, pident, etc.)
Plasmid-map feature presets
Description
Plasmid-map feature presets
Usage
scale_feature_fill_plasmid(..., limits = NULL)
scale_feature_shape_plasmid(..., limits = NULL, guide = "none")
Arguments
... |
Additional scale arguments. |
limits |
Optional feature-type order. |
guide |
Guide used by the shape preset. |
Value
A feature fill or shape scale.
Feature shape scale
Description
Maps feature categories to the geometry types understood by
geom_feature(), including full/compact/promoter/primer arrows, markers,
blocks, capped lines, chevrons, and lollipops. capped_line is an
unfilled interval with short terminal caps.
Shape values affect the actual feature geometry as well as its legend key.
Usage
scale_feature_shape_manual(
...,
values,
name = "Feature",
limits = NULL,
guide = "none"
)
Arguments
... |
Arguments passed to |
values |
A named or unnamed character vector of feature geometry names. |
name |
Scale and guide title, default |
limits |
Optional category order. Named |
guide |
Guide specification. The default is |
Value
A ggplot2 discrete scale for the feature_shape aesthetic.
Colour residue cells by chemical group
Description
A standard discrete fill scale for geom_residue(). DNA/RNA use separate
colours for A, C, G and T/U; AA groups residues by side-chain chemistry.
Gaps, stops and ambiguous symbols are neutral. Lowercase symbols receive
the same colours as uppercase symbols. The chemistry colours follow ggmsa;
this scale does not compute conservation or an alignment.
Usage
scale_fill_residue(alphabet = c("DNA", "RNA", "AA"), ...)
Arguments
alphabet |
Explicit DNA, RNA or AA palette. Defaults to DNA for direct calls. geom_residue() uses the data's alphabet column, otherwise AA. |
... |
Additional arguments to |
Value
A ggplot2 discrete fill scale. Explicit user scales take priority over a residue layer's inferred default.
Examples
cells <- as_ggchord_alignment(c(A = "AC-G", B = "ACTG"), "DNA")
ggplot2::ggplot(cells, aes(alignment_column, accver, label = symbol)) +
geom_residue() +
scale_fill_residue("DNA", guide = "none")
Gene, feature and region fill scales
Description
Gene, feature and region fill scales
Usage
scale_gene_fill_manual(..., values)
scale_feature_fill_manual(..., values, limits = NULL)
scale_region_fill_manual(..., values)
Arguments
... |
Arguments passed to |
values |
A set of fill values to map data values to. |
limits |
Optional display order. Named feature values use their name order by default. |
Value
A ggplot2 scale.
Scales for point links and alignment segments
Description
Point-link aesthetics are independent of sequence and ribbon aesthetics. Automatically generated numeric pident mappings use the 0-100 domain and ticks 0/50/80/90/95/100. Explicit scales keep their own limits and breaks.
Usage
scale_link_colour_manual(..., values)
scale_link_color_manual(..., values)
scale_link_alpha_manual(..., values)
scale_link_linewidth_manual(..., values)
scale_link_linetype_manual(..., values)
scale_link_colour_gradientn(...)
scale_link_color_gradientn(...)
scale_link_alpha_continuous(...)
scale_link_linewidth_continuous(...)
Arguments
... |
Arguments passed to the corresponding ggplot2 scale. |
values |
Manual aesthetic values. |
Value
A ggplot2 scale.
Ribbon alpha, outline and linetype scales
Description
Ribbon alpha, outline and linetype scales
Usage
scale_ribbon_alpha_continuous(..., range = NULL)
scale_ribbon_alpha_manual(..., values)
scale_ribbon_colour_manual(..., values)
scale_ribbon_color_manual(..., values)
scale_ribbon_linetype_manual(..., values)
Arguments
... |
Arguments passed to the corresponding ggplot2 scale. |
range |
Output alpha range for a continuous scale. NULL uses the corresponding ggplot2 scale's default range. |
values |
Manual aesthetic values. |
Value
A ggplot2 scale.
Ribbon fill scales
Description
Ribbon fill scales
Usage
scale_ribbon_fill_stepsn(
...,
colours,
values = NULL,
colors,
guide = ggplot2::guide_coloursteps(available_aes = "ribbon_fill")
)
scale_ribbon_fill_gradientn(
...,
colours,
values = NULL,
colors,
guide = ggplot2::guide_colourbar(available_aes = "ribbon_fill")
)
scale_ribbon_fill_manual(..., values)
scale_ribbon_fill_identity(...)
Arguments
... |
Arguments passed to the corresponding ggplot2 scale. |
colours, colors |
Gradient colours. |
values |
Manual values, or positions for gradient colours where supported by the corresponding ggplot2 scale. |
guide |
A guide object; defaults accept the |
Value
A ggplot2 scale.
Sequence colour scales
Description
Sequence colour scales
Usage
scale_seq_colour_manual(..., values)
scale_seq_color_manual(..., values)
Arguments
... |
Arguments passed to |
values |
A set of aesthetic values to map data values to. |
Value
A ggplot2 scale.
Genomic sequence position scale
Description
Controls major/minor genomic position breaks and labels independently for
every sequence. The default domain is each sequence's [1, length] range;
linear source-coordinate axes use the retained original genomic interval.
This scale configures sequence axes across supported coordinate modes. To add
an independent bp reference bar in a linear display, use geom_seq_scale().
Usage
scale_seq_position_continuous(
name = ggplot2::waiver(),
breaks = ggplot2::waiver(),
minor_breaks = ggplot2::waiver(),
labels = ggplot2::waiver(),
limits = NULL,
expand = ggplot2::waiver(),
oob = scales::censor,
transform = "identity",
n.breaks = 6,
coordinates = c("relative", "source"),
sequences = NULL,
...
)
Arguments
name |
Scale name; position guides are disabled by default. |
breaks, minor_breaks, labels, limits, expand, oob, transform, n.breaks |
Standard continuous-scale controls. |
coordinates |
In linear layouts, use relative locus coordinates or
original source coordinates retained by |
sequences |
Optional character vector selecting sequence axes by their
displayed |
... |
Additional arguments passed to |
Value
A ggplot2 continuous scale for the seq_position role.
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
ggchord(seq_data = seqs) +
geom_seq() +
coord_collinear() +
scale_seq_position_continuous(n.breaks = 4)
Explicit sequence ring scale
Description
Maps user-defined ring identifiers to positive sequence radii. Ring
membership is supplied with geom_seq(aes(seq_ring = ...)); ggchord never
guesses the number, order, or spacing of rings.
Usage
scale_seq_ring_manual(
...,
values,
name = "Ring",
limits = NULL,
guide = "none"
)
Arguments
... |
Arguments passed to |
values |
A named or unnamed numeric vector of positive radii. |
name |
Scale title. The guide is hidden by default because the scale controls geometry rather than a visible legend aesthetic. |
limits |
Optional ring order. |
guide |
Guide specification, default |
Value
A ggplot2 discrete scale for the seq_ring role.
Set a track's fill or colour mapping
Description
Set a track's fill or colour mapping
Usage
scale_track_fill_gradientn(track, ..., colours, guide = NULL)
scale_track_fill_manual(track, ..., values)
scale_track_colour_gradientn(track, ..., colours, guide = NULL)
scale_track_colour_manual(track, ..., values)
Arguments
track |
Track ID. |
... |
Standard ggplot2 scale arguments. |
colours |
Gradient colours. |
guide |
Optional standard guide for the fill/colour scale. |
values |
Manual category colours. |
Value
A standard scale scoped to the named track's visual role.
Examples
scale_track_fill_gradientn("gc", colours = c("navy", "white", "orange"))
Set a named track's numerical height scale
Description
Uses an independent continuous scale for each track ID. The same ID shares
its domain across sequences, windows and layers. The scale controls height,
not colour. A numerical axis is drawn by default; guide = "none" hides it.
Usage
scale_track_value_continuous(
track,
name = track,
limits = NULL,
breaks = ggplot2::waiver(),
labels = ggplot2::waiver(),
transform = "identity",
oob = scales::censor,
unit = NULL,
guide = c("axis", "none"),
...
)
Arguments
track |
Track ID from |
name |
Axis title, default the track ID. |
limits, breaks, labels, transform, oob |
Standard continuous-scale controls. |
unit |
Optional data-unit label retained in track exports. |
guide |
|
... |
Additional ggplot2 continuous-scale arguments. |
Value
A ggplot2 scale, scoped to this track.
Examples
scale_track_value_continuous("coverage", limits = c(0, 100), unit = "reads")
scale_track_value_continuous("gc", limits = c(0, 1),
guide = ggplot2::guide_axis(theme = ggplot2::theme(
axis.text = ggplot2::element_text(size = 9, colour = "#345F58"))))
Prepare independent windows for a segmented linear display
Description
Crops through focus_ggchord_data() while retaining one sequence per
window. Pass segments to coord_collinear() to place those sequences in
shared display rows with explicit gaps and local reversals. Coordinates in
the returned tables remain window-local and are never concatenated.
Usage
segment_ggchord_data(
seq_data,
ribbon_data = NULL,
gene_data = NULL,
windows,
point_data = NULL,
cross_gap = c("split", "drop"),
max_links = 10000,
feature_data = NULL
)
Arguments
seq_data |
Full sequence table with unique |
ribbon_data |
Optional paired interval table. |
gene_data |
Optional gene or generic feature table, including segments. |
windows |
Table with |
point_data |
Optional point links with |
cross_gap |
How to handle interval links clipped by selected windows. |
max_links |
Positive integer upper bound on candidate ribbon/point copies. Increase explicitly for larger, intentionally overlapping views. |
feature_data |
Unified annotation input; mutually exclusive with gene_data. |
Details
cross_gap = "split" retains only the parts of each ribbon's linear
endpoint correspondence that lie in both selected windows. Omitted regions
are never bridged by one ribbon polygon. "drop" retains only links fully
contained in a query and subject window. This is a display projection, not
realignment. Point links survive only when both endpoints are retained.
Overlapping windows can deliberately duplicate a source row; provenance
identifies each copy, and max_links bounds the candidate expansion before
allocation. Order in the window table is display order within each row.
Value
A list containing focused seq_data, ribbon_data, gene_data,
point_data, segments for the coordinate system, reversible source to
window transforms, and a report with input row numbers for every
output connection and omitted input rows. Each window retains its own
source accession, origin, full length and truncation flags.
See Also
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
windows <- tibble(
accver = rep(seqs$accver[1], 2),
start = c(1, floor(seqs$length[1] * .65)),
end = c(floor(seqs$length[1] * .4), seqs$length[1]),
locus_id = c("left_window", "right_window"), row_id = seqs$accver[1]
)
segment_ggchord_data(slice_head(seqs, n = 1), windows = windows)
Example sequence data
Description
Sequence length data for ggchord demonstration
Usage
seq_data_example
Format
A data frame containing columns: accver, length
Source-backed alignment and coding sequence teaching inputs
Description
Prepared inputs for sequence-detail, Dotplot and Fusion examples. File
readers are demonstrated separately; these tables require no checkout or
working-directory configuration. Rebuild with
data-raw/generate_website_data.R.
Usage
sequence_detail_example
Format
A named list: plasmid_source retains the complete pUC19 input;
paf is the complete 11-HSP EMALE pair; dna_alignment
and protein_alignment are long-form observed alignment cells;
aligned_strings contains the original gapped DNA strings;
coding_genome, coding_features and coding_proteins retain the genomic,
annotation and protein inputs for the CDS translation example.
protein_hits and source_coding_features retain the full protein
projection inputs with source-file provenance. DNA
coordinates are in bp, protein coordinates in residues. No alignment gaps
or coding relationships are inferred to improve a plot.
Source
Repository examples/alignment/ and examples/format-inputs/,
with upstream provenance in their README files and checksums in
data-raw/website-data-sources.tsv.
Examples
data(sequence_detail_example)
head(sequence_detail_example$paf)
Minimal single-genome gene fixture
Description
Minimal single-genome gene fixture
Format
A data frame with accver, start, end, strand, and anno.
Source
examples/single-genome/features.tsv.
Minimal single-genome sequence fixture
Description
Minimal single-genome sequence fixture
Format
A one-row data frame with accver and length.
Source
examples/single-genome/minimal.fasta.
Bundle ribbons as a ggchord stat
Description
A layer form of bundle_ggchord_ribbons() that computes bundles before the
shared chord geometry and exposes after_stat(bundle_n),
after_stat(bundle_weight), and after_stat(density).
Usage
stat_ribbon_bundle(
mapping = NULL,
data = NULL,
bins = 80L,
min_bundle = 2L,
weight = c("length", "count", "pident"),
group_by = NULL,
position = "identity",
show.legend = TRUE,
inherit.aes = FALSE,
...
)
Arguments
mapping, data |
Standard layer mapping and data arguments. |
bins, min_bundle, weight, group_by |
Passed to
|
position, show.legend, inherit.aes |
Standard ggplot2 layer arguments. |
... |
Ribbon geometry and appearance arguments passed to
|
Value
A ggchord ribbon layer.
See Also
Compute local ribbon density as a ggchord stat
Description
Keeps one output ribbon per input row while measuring density in normalized
query/subject midpoint bins. The computed variables are the same as
stat_ribbon_bundle(), so density can be mapped with
aes(ribbon_alpha = after_stat(density)).
Usage
stat_ribbon_density(
mapping = NULL,
data = NULL,
bins = 80L,
weight = c("length", "count", "pident"),
group_by = NULL,
position = "identity",
show.legend = TRUE,
inherit.aes = FALSE,
...
)
Arguments
mapping, data |
Standard layer mapping and data arguments. |
bins |
Positive integer number of normalized midpoint bins per sequence. |
weight |
Density weight: |
group_by |
Optional columns that define independent density groups. |
position, show.legend, inherit.aes |
Standard ggplot2 layer arguments. |
... |
Ribbon geometry and appearance arguments passed to
|
Value
A ggchord ribbon layer.
See Also
ggchord themes
Description
Complete themes for chord diagrams. Besides ordinary ggplot2 theme elements, these functions control automatic sequence axes, chord labels and the appearance and placement of guides belonging to each ggchord role. Palettes, breaks, labels and guide ordering remain scale/guide concerns.
Usage
theme_ggchord(
axis = NULL,
axis.line = NULL,
axis.ticks = NULL,
axis.minor.ticks = NULL,
axis.text = NULL,
axis.gap = NULL,
axis.ticks.length = NULL,
axis.minor.ticks.length = NULL,
axis.text.offset = NULL,
axis.text.orientation = NULL,
axis.text.check.overlap = NULL,
seq.label = NULL,
gene.label = NULL,
gene.label.segment = NULL,
feature.label = NULL,
feature.label.segment = NULL,
restriction.label = NULL,
restriction.label.segment = NULL,
seq.center.label = NULL,
seq.center.name = NULL,
seq.center.length = NULL,
legend.seq = NULL,
legend.seq.position = NULL,
legend.seq.direction = NULL,
legend.seq.background = NULL,
legend.seq.key = NULL,
legend.seq.key.size = NULL,
legend.seq.key.width = NULL,
legend.seq.key.height = NULL,
legend.seq.text = NULL,
legend.seq.text.position = NULL,
legend.seq.title = NULL,
legend.seq.title.position = NULL,
legend.seq.margin = NULL,
legend.seq.spacing = NULL,
legend.link = NULL,
legend.link.position = NULL,
legend.link.direction = NULL,
legend.link.background = NULL,
legend.link.key = NULL,
legend.link.key.size = NULL,
legend.link.key.width = NULL,
legend.link.key.height = NULL,
legend.link.text = NULL,
legend.link.text.position = NULL,
legend.link.title = NULL,
legend.link.title.position = NULL,
legend.link.margin = NULL,
legend.link.spacing = NULL,
legend.ribbon = NULL,
legend.ribbon.position = NULL,
legend.ribbon.direction = NULL,
legend.ribbon.background = NULL,
legend.ribbon.key = NULL,
legend.ribbon.key.size = NULL,
legend.ribbon.key.width = NULL,
legend.ribbon.key.height = NULL,
legend.ribbon.text = NULL,
legend.ribbon.text.position = NULL,
legend.ribbon.title = NULL,
legend.ribbon.title.position = NULL,
legend.ribbon.margin = NULL,
legend.ribbon.spacing = NULL,
legend.ribbon.ticks = NULL,
legend.ribbon.ticks.length = NULL,
legend.ribbon.axis.line = NULL,
legend.gene = NULL,
legend.gene.position = NULL,
legend.gene.direction = NULL,
legend.gene.background = NULL,
legend.gene.key = NULL,
legend.gene.key.size = NULL,
legend.gene.key.width = NULL,
legend.gene.key.height = NULL,
legend.gene.text = NULL,
legend.gene.text.position = NULL,
legend.gene.title = NULL,
legend.gene.title.position = NULL,
legend.gene.margin = NULL,
legend.gene.spacing = NULL,
legend.feature = NULL,
legend.feature.position = NULL,
legend.feature.direction = NULL,
legend.feature.background = NULL,
legend.feature.key = NULL,
legend.feature.key.size = NULL,
legend.feature.key.width = NULL,
legend.feature.key.height = NULL,
legend.feature.text = NULL,
legend.feature.text.position = NULL,
legend.feature.title = NULL,
legend.feature.title.position = NULL,
legend.feature.margin = NULL,
legend.feature.spacing = NULL,
legend.region = NULL,
legend.region.position = NULL,
legend.region.direction = NULL,
legend.region.background = NULL,
legend.region.key = NULL,
legend.region.key.size = NULL,
legend.region.key.width = NULL,
legend.region.key.height = NULL,
legend.region.text = NULL,
legend.region.text.position = NULL,
legend.region.title = NULL,
legend.region.title.position = NULL,
legend.region.margin = NULL,
legend.region.spacing = NULL,
...
)
theme_ggchord_minimal(
axis = NULL,
axis.line = NULL,
axis.ticks = NULL,
axis.minor.ticks = NULL,
axis.text = NULL,
axis.gap = NULL,
axis.ticks.length = NULL,
axis.minor.ticks.length = NULL,
axis.text.offset = NULL,
axis.text.orientation = NULL,
axis.text.check.overlap = NULL,
seq.label = NULL,
gene.label = NULL,
gene.label.segment = NULL,
feature.label = NULL,
feature.label.segment = NULL,
restriction.label = NULL,
restriction.label.segment = NULL,
seq.center.label = NULL,
seq.center.name = NULL,
seq.center.length = NULL,
legend.seq = NULL,
legend.seq.position = NULL,
legend.seq.direction = NULL,
legend.seq.background = NULL,
legend.seq.key = NULL,
legend.seq.key.size = NULL,
legend.seq.key.width = NULL,
legend.seq.key.height = NULL,
legend.seq.text = NULL,
legend.seq.text.position = NULL,
legend.seq.title = NULL,
legend.seq.title.position = NULL,
legend.seq.margin = NULL,
legend.seq.spacing = NULL,
legend.link = NULL,
legend.link.position = NULL,
legend.link.direction = NULL,
legend.link.background = NULL,
legend.link.key = NULL,
legend.link.key.size = NULL,
legend.link.key.width = NULL,
legend.link.key.height = NULL,
legend.link.text = NULL,
legend.link.text.position = NULL,
legend.link.title = NULL,
legend.link.title.position = NULL,
legend.link.margin = NULL,
legend.link.spacing = NULL,
legend.ribbon = NULL,
legend.ribbon.position = NULL,
legend.ribbon.direction = NULL,
legend.ribbon.background = NULL,
legend.ribbon.key = NULL,
legend.ribbon.key.size = NULL,
legend.ribbon.key.width = NULL,
legend.ribbon.key.height = NULL,
legend.ribbon.text = NULL,
legend.ribbon.text.position = NULL,
legend.ribbon.title = NULL,
legend.ribbon.title.position = NULL,
legend.ribbon.margin = NULL,
legend.ribbon.spacing = NULL,
legend.ribbon.ticks = NULL,
legend.ribbon.ticks.length = NULL,
legend.ribbon.axis.line = NULL,
legend.gene = NULL,
legend.gene.position = NULL,
legend.gene.direction = NULL,
legend.gene.background = NULL,
legend.gene.key = NULL,
legend.gene.key.size = NULL,
legend.gene.key.width = NULL,
legend.gene.key.height = NULL,
legend.gene.text = NULL,
legend.gene.text.position = NULL,
legend.gene.title = NULL,
legend.gene.title.position = NULL,
legend.gene.margin = NULL,
legend.gene.spacing = NULL,
legend.feature = NULL,
legend.feature.position = NULL,
legend.feature.direction = NULL,
legend.feature.background = NULL,
legend.feature.key = NULL,
legend.feature.key.size = NULL,
legend.feature.key.width = NULL,
legend.feature.key.height = NULL,
legend.feature.text = NULL,
legend.feature.text.position = NULL,
legend.feature.title = NULL,
legend.feature.title.position = NULL,
legend.feature.margin = NULL,
legend.feature.spacing = NULL,
legend.region = NULL,
legend.region.position = NULL,
legend.region.direction = NULL,
legend.region.background = NULL,
legend.region.key = NULL,
legend.region.key.size = NULL,
legend.region.key.width = NULL,
legend.region.key.height = NULL,
legend.region.text = NULL,
legend.region.text.position = NULL,
legend.region.title = NULL,
legend.region.title.position = NULL,
legend.region.margin = NULL,
legend.region.spacing = NULL,
...
)
theme_ggchord_dark(
axis = NULL,
axis.line = NULL,
axis.ticks = NULL,
axis.minor.ticks = NULL,
axis.text = NULL,
axis.gap = NULL,
axis.ticks.length = NULL,
axis.minor.ticks.length = NULL,
axis.text.offset = NULL,
axis.text.orientation = NULL,
axis.text.check.overlap = NULL,
seq.label = NULL,
gene.label = NULL,
gene.label.segment = NULL,
feature.label = NULL,
feature.label.segment = NULL,
restriction.label = NULL,
restriction.label.segment = NULL,
seq.center.label = NULL,
seq.center.name = NULL,
seq.center.length = NULL,
legend.seq = NULL,
legend.seq.position = NULL,
legend.seq.direction = NULL,
legend.seq.background = NULL,
legend.seq.key = NULL,
legend.seq.key.size = NULL,
legend.seq.key.width = NULL,
legend.seq.key.height = NULL,
legend.seq.text = NULL,
legend.seq.text.position = NULL,
legend.seq.title = NULL,
legend.seq.title.position = NULL,
legend.seq.margin = NULL,
legend.seq.spacing = NULL,
legend.link = NULL,
legend.link.position = NULL,
legend.link.direction = NULL,
legend.link.background = NULL,
legend.link.key = NULL,
legend.link.key.size = NULL,
legend.link.key.width = NULL,
legend.link.key.height = NULL,
legend.link.text = NULL,
legend.link.text.position = NULL,
legend.link.title = NULL,
legend.link.title.position = NULL,
legend.link.margin = NULL,
legend.link.spacing = NULL,
legend.ribbon = NULL,
legend.ribbon.position = NULL,
legend.ribbon.direction = NULL,
legend.ribbon.background = NULL,
legend.ribbon.key = NULL,
legend.ribbon.key.size = NULL,
legend.ribbon.key.width = NULL,
legend.ribbon.key.height = NULL,
legend.ribbon.text = NULL,
legend.ribbon.text.position = NULL,
legend.ribbon.title = NULL,
legend.ribbon.title.position = NULL,
legend.ribbon.margin = NULL,
legend.ribbon.spacing = NULL,
legend.ribbon.ticks = NULL,
legend.ribbon.ticks.length = NULL,
legend.ribbon.axis.line = NULL,
legend.gene = NULL,
legend.gene.position = NULL,
legend.gene.direction = NULL,
legend.gene.background = NULL,
legend.gene.key = NULL,
legend.gene.key.size = NULL,
legend.gene.key.width = NULL,
legend.gene.key.height = NULL,
legend.gene.text = NULL,
legend.gene.text.position = NULL,
legend.gene.title = NULL,
legend.gene.title.position = NULL,
legend.gene.margin = NULL,
legend.gene.spacing = NULL,
legend.feature = NULL,
legend.feature.position = NULL,
legend.feature.direction = NULL,
legend.feature.background = NULL,
legend.feature.key = NULL,
legend.feature.key.size = NULL,
legend.feature.key.width = NULL,
legend.feature.key.height = NULL,
legend.feature.text = NULL,
legend.feature.text.position = NULL,
legend.feature.title = NULL,
legend.feature.title.position = NULL,
legend.feature.margin = NULL,
legend.feature.spacing = NULL,
legend.region = NULL,
legend.region.position = NULL,
legend.region.direction = NULL,
legend.region.background = NULL,
legend.region.key = NULL,
legend.region.key.size = NULL,
legend.region.key.width = NULL,
legend.region.key.height = NULL,
legend.region.text = NULL,
legend.region.text.position = NULL,
legend.region.title = NULL,
legend.region.title.position = NULL,
legend.region.margin = NULL,
legend.region.spacing = NULL,
...
)
theme_ggchord_publication(
axis = NULL,
axis.line = NULL,
axis.ticks = NULL,
axis.minor.ticks = NULL,
axis.text = NULL,
axis.gap = NULL,
axis.ticks.length = NULL,
axis.minor.ticks.length = NULL,
axis.text.offset = NULL,
axis.text.orientation = NULL,
axis.text.check.overlap = NULL,
seq.label = NULL,
gene.label = NULL,
gene.label.segment = NULL,
feature.label = NULL,
feature.label.segment = NULL,
restriction.label = NULL,
restriction.label.segment = NULL,
seq.center.label = NULL,
seq.center.name = NULL,
seq.center.length = NULL,
legend.seq = NULL,
legend.seq.position = NULL,
legend.seq.direction = NULL,
legend.seq.background = NULL,
legend.seq.key = NULL,
legend.seq.key.size = NULL,
legend.seq.key.width = NULL,
legend.seq.key.height = NULL,
legend.seq.text = NULL,
legend.seq.text.position = NULL,
legend.seq.title = NULL,
legend.seq.title.position = NULL,
legend.seq.margin = NULL,
legend.seq.spacing = NULL,
legend.link = NULL,
legend.link.position = NULL,
legend.link.direction = NULL,
legend.link.background = NULL,
legend.link.key = NULL,
legend.link.key.size = NULL,
legend.link.key.width = NULL,
legend.link.key.height = NULL,
legend.link.text = NULL,
legend.link.text.position = NULL,
legend.link.title = NULL,
legend.link.title.position = NULL,
legend.link.margin = NULL,
legend.link.spacing = NULL,
legend.ribbon = NULL,
legend.ribbon.position = NULL,
legend.ribbon.direction = NULL,
legend.ribbon.background = NULL,
legend.ribbon.key = NULL,
legend.ribbon.key.size = NULL,
legend.ribbon.key.width = NULL,
legend.ribbon.key.height = NULL,
legend.ribbon.text = NULL,
legend.ribbon.text.position = NULL,
legend.ribbon.title = NULL,
legend.ribbon.title.position = NULL,
legend.ribbon.margin = NULL,
legend.ribbon.spacing = NULL,
legend.ribbon.ticks = NULL,
legend.ribbon.ticks.length = NULL,
legend.ribbon.axis.line = NULL,
legend.gene = NULL,
legend.gene.position = NULL,
legend.gene.direction = NULL,
legend.gene.background = NULL,
legend.gene.key = NULL,
legend.gene.key.size = NULL,
legend.gene.key.width = NULL,
legend.gene.key.height = NULL,
legend.gene.text = NULL,
legend.gene.text.position = NULL,
legend.gene.title = NULL,
legend.gene.title.position = NULL,
legend.gene.margin = NULL,
legend.gene.spacing = NULL,
legend.feature = NULL,
legend.feature.position = NULL,
legend.feature.direction = NULL,
legend.feature.background = NULL,
legend.feature.key = NULL,
legend.feature.key.size = NULL,
legend.feature.key.width = NULL,
legend.feature.key.height = NULL,
legend.feature.text = NULL,
legend.feature.text.position = NULL,
legend.feature.title = NULL,
legend.feature.title.position = NULL,
legend.feature.margin = NULL,
legend.feature.spacing = NULL,
legend.region = NULL,
legend.region.position = NULL,
legend.region.direction = NULL,
legend.region.background = NULL,
legend.region.key = NULL,
legend.region.key.size = NULL,
legend.region.key.width = NULL,
legend.region.key.height = NULL,
legend.region.text = NULL,
legend.region.text.position = NULL,
legend.region.title = NULL,
legend.region.title.position = NULL,
legend.region.margin = NULL,
legend.region.spacing = NULL,
...
)
theme_ggchord_plasmid(
axis = NULL,
axis.line = NULL,
axis.ticks = NULL,
axis.minor.ticks = NULL,
axis.text = NULL,
axis.gap = NULL,
axis.ticks.length = NULL,
axis.minor.ticks.length = NULL,
axis.text.offset = NULL,
axis.text.orientation = NULL,
axis.text.check.overlap = NULL,
seq.label = NULL,
gene.label = NULL,
gene.label.segment = NULL,
feature.label = NULL,
feature.label.segment = NULL,
restriction.label = NULL,
restriction.label.segment = NULL,
seq.center.label = NULL,
seq.center.name = NULL,
seq.center.length = NULL,
legend.seq = NULL,
legend.seq.position = NULL,
legend.seq.direction = NULL,
legend.seq.background = NULL,
legend.seq.key = NULL,
legend.seq.key.size = NULL,
legend.seq.key.width = NULL,
legend.seq.key.height = NULL,
legend.seq.text = NULL,
legend.seq.text.position = NULL,
legend.seq.title = NULL,
legend.seq.title.position = NULL,
legend.seq.margin = NULL,
legend.seq.spacing = NULL,
legend.link = NULL,
legend.link.position = NULL,
legend.link.direction = NULL,
legend.link.background = NULL,
legend.link.key = NULL,
legend.link.key.size = NULL,
legend.link.key.width = NULL,
legend.link.key.height = NULL,
legend.link.text = NULL,
legend.link.text.position = NULL,
legend.link.title = NULL,
legend.link.title.position = NULL,
legend.link.margin = NULL,
legend.link.spacing = NULL,
legend.ribbon = NULL,
legend.ribbon.position = NULL,
legend.ribbon.direction = NULL,
legend.ribbon.background = NULL,
legend.ribbon.key = NULL,
legend.ribbon.key.size = NULL,
legend.ribbon.key.width = NULL,
legend.ribbon.key.height = NULL,
legend.ribbon.text = NULL,
legend.ribbon.text.position = NULL,
legend.ribbon.title = NULL,
legend.ribbon.title.position = NULL,
legend.ribbon.margin = NULL,
legend.ribbon.spacing = NULL,
legend.ribbon.ticks = NULL,
legend.ribbon.ticks.length = NULL,
legend.ribbon.axis.line = NULL,
legend.gene = NULL,
legend.gene.position = NULL,
legend.gene.direction = NULL,
legend.gene.background = NULL,
legend.gene.key = NULL,
legend.gene.key.size = NULL,
legend.gene.key.width = NULL,
legend.gene.key.height = NULL,
legend.gene.text = NULL,
legend.gene.text.position = NULL,
legend.gene.title = NULL,
legend.gene.title.position = NULL,
legend.gene.margin = NULL,
legend.gene.spacing = NULL,
legend.feature = NULL,
legend.feature.position = NULL,
legend.feature.direction = NULL,
legend.feature.background = NULL,
legend.feature.key = NULL,
legend.feature.key.size = NULL,
legend.feature.key.width = NULL,
legend.feature.key.height = NULL,
legend.feature.text = NULL,
legend.feature.text.position = NULL,
legend.feature.title = NULL,
legend.feature.title.position = NULL,
legend.feature.margin = NULL,
legend.feature.spacing = NULL,
legend.region = NULL,
legend.region.position = NULL,
legend.region.direction = NULL,
legend.region.background = NULL,
legend.region.key = NULL,
legend.region.key.size = NULL,
legend.region.key.width = NULL,
legend.region.key.height = NULL,
legend.region.text = NULL,
legend.region.text.position = NULL,
legend.region.title = NULL,
legend.region.title.position = NULL,
legend.region.margin = NULL,
legend.region.spacing = NULL,
...
)
Arguments
axis |
|
axis.line, axis.ticks, axis.minor.ticks |
Axis line elements. |
axis.text |
Axis text element. |
axis.gap, axis.ticks.length, axis.minor.ticks.length, axis.text.offset |
Scalar |
axis.text.orientation |
One of |
axis.text.check.overlap |
Whether overlapping axis labels are hidden. Defaults to TRUE.
Automatically positioned circular parallel labels, including combined seam
strings, can receive bounded inward or outward radial clearance around
feature polygons and fixed annotation-leader roots. Internal and exterior
annotation leaders route around the resolved axis text; mutable shoulders
do not feed back into axis placement. Automatic strings stay in a near-
backbone channel. Origin/end strings take priority and remain visible;
an automatic endpoint may use either readable side of its tick, with a
bounded tangential gap up to 4 mm, to clear fixed feature exit rays.
Unresolved endpoint clearance is reported as |
seq.label, gene.label, feature.label, restriction.label, seq.center.label, seq.center.name, seq.center.length |
Text elements for sequence, gene, feature, restriction-site and circular centre labels. |
gene.label.segment, feature.label.segment, restriction.label.segment |
Line elements for gene, feature and restriction-site leader lines. |
legend.seq, legend.ribbon, legend.gene, legend.feature, legend.region |
|
legend.seq.position, legend.ribbon.position, legend.gene.position, legend.feature.position, legend.region.position |
Per-role guide positions. |
legend.seq.direction, legend.ribbon.direction, legend.gene.direction, legend.feature.direction, legend.region.direction |
Per-role directions. |
legend.seq.background, legend.ribbon.background, legend.gene.background, legend.feature.background, legend.region.background |
Per-role backgrounds. |
legend.seq.key, legend.ribbon.key, legend.gene.key, legend.feature.key, legend.region.key |
Per-role key elements. |
legend.seq.key.size, legend.seq.key.width, legend.seq.key.height, legend.ribbon.key.size, legend.ribbon.key.width, legend.ribbon.key.height, legend.gene.key.size, legend.gene.key.width, legend.gene.key.height, legend.feature.key.size, legend.feature.key.width, legend.feature.key.height, legend.region.key.size, legend.region.key.width, legend.region.key.height |
Per-role key dimensions. Automatic Identity rulers measure their boundary labels independently of generic legend swatch sizes. Set a Ribbon-specific dimension or an explicit guide for a manual ruler length. |
legend.seq.text, legend.ribbon.text, legend.gene.text, legend.feature.text, legend.region.text |
Per-role text elements. |
legend.seq.text.position, legend.ribbon.text.position, legend.gene.text.position, legend.feature.text.position, legend.region.text.position |
Per-role text positions. |
legend.seq.title, legend.ribbon.title, legend.gene.title, legend.feature.title, legend.region.title |
Per-role title elements. |
legend.seq.title.position, legend.ribbon.title.position, legend.gene.title.position, legend.feature.title.position, legend.region.title.position |
Per-role title positions. |
legend.seq.margin, legend.ribbon.margin, legend.gene.margin, legend.feature.margin, legend.region.margin |
Per-role margins. |
legend.seq.spacing, legend.ribbon.spacing, legend.gene.spacing, legend.feature.spacing, legend.region.spacing |
Per-role spacing. |
legend.link, legend.link.position, legend.link.direction, legend.link.background, legend.link.key, legend.link.key.size, legend.link.key.width, legend.link.key.height, legend.link.text, legend.link.text.position, legend.link.title, legend.link.title.position, legend.link.margin, legend.link.spacing |
Point-link guide appearance; follows the same role-specific rules. |
legend.ribbon.ticks, legend.ribbon.axis.line |
Ribbon colourbar lines. |
legend.ribbon.ticks.length |
Ribbon colourbar tick length. |
... |
Standard ggplot2 theme arguments, including common text, plot and legend settings. Common legend settings also supply role inheritance. Removed underscore-style arguments produce a migration error. |
Value
A complete ggplot2 theme carrying ggchord appearance settings.
Appearance settings
Ordinary text, panel, title and shared legend settings follow ggplot2.
Sequence-axis settings control automatic axis decoration, not genomic
break selection; use scale_seq_position_continuous() for breaks and labels.
Role text and leader elements style non-data annotation. Role legend
settings inherit common legend appearance, while scale and guide objects
continue to own palettes, breaks and ordering. Physical spacings require
scalar absolute grid::unit() values; axis.text.orientation is scalar.
The preset themes share this signature and provide appearance defaults.
Native detailed configuration
Use standard theme() with the registered ggchord.axis.*, ggchord.seq.label,
ggchord.gene.label, ggchord.feature.label and leader elements. Axis gap,
tick lengths, text offset/orientation and overlap settings also have
ggchord.axis.* entries. Absolute scalar units are required for spacings.
Existing short arguments remain convenient aliases; do not supply both
spellings for one setting in the same call. Later theme() entries override
earlier defaults following ordinary ggplot2 field-wise merging.
Quantitative axis decoration uses ggchord.track.axis.line, ggchord.track.axis.text and ggchord.track.axis.title, plus absolute ggchord.track.axis.text.offset and ggchord.track.axis.title.offset. These inherit sequence-axis/text styling; each track may override its own decoration through guide_axis(theme = theme(axis.text = ..., axis.title = ..., axis.line = ...)) in scale_track_value_continuous(). Numerical domains, units, breaks and labels still belong to that scale; colours to scoped fill/colour scales; physical bands to position_track(). Theme changes never filter data, alter HSPs or choose sequence directions.
Standard ggplot2 settings
Standard text, plot title/caption/tag, backgrounds, plot margins and common
legend settings remain available through ..., for example
theme_ggchord(text = element_text(size = 12)).
Only ggchord-specific settings appear as explicit formals for IDE argument
completion. An IDE that additionally expands upstream dots may still offer
upstream suggestions; this package controls its own function signature.
Translate source-backed CDS with exact codon provenance
Description
Uses the complete observed codons in build_ggchord_cds(), including codons
split across segments. Extraction follows biological segment order; negative
DNA/RNA strands are complemented. Biostrings supplies genetic codes and
translation, and is required only when this function is called.
Usage
translate_ggchord_cds(
cds,
sequences,
alphabet = c("DNA", "RNA"),
initiation = c("literal", "start"),
ambiguous = c("error", "solve")
)
Arguments
cds |
A map from |
sequences |
Named character vector of complete forward source strings,
or a data frame with unique accver and sequence (e.g. |
alphabet |
Explicit |
initiation |
|
ambiguous |
|
Details
A known genetic_code is required for every model. No sequence, phase,
missing end or translation exception is inferred. Stops remain *, including
internal stops; they are not replaced or removed. The result is an observed
translation, not a validation of gene function or a predicted full protein.
Partial-end trimming follows the supplied CDS map and is reported in models.
Value
A list with models (coding_sequence, protein_sequence and policies),
nucleotides (one row per observed coding base) and residues (one row per
codon, with source_positions, source_cds_rows and source_cds_segments list
columns in transcription order). Residues use the CDS feature_id as their
observed-protein accver, not an inferred external accession. Nucleotides
retain genomic source_accver/source_position and codon_index/codon_base;
both tables can be displayed with geom_residue(). Source input and the
original CDS map remain in provenance. No alignment is computed.
See Also
https://bioconductor.org/packages/Biostrings
Examples
# Explicit synthetic codon contract, not a biological annotation claim.
if (requireNamespace("Biostrings", quietly = TRUE)) {
coding <- data.frame(feature_id = "cds", accver = "source",
start = 1, end = 6, strand = "+", phase = 0)
cds <- build_ggchord_cds(coding, genetic_code = 11)
translate_ggchord_cds(cds, c(source = "ATGTAA"))$residues
}
Validate ggchord input data before plotting
Description
Performs structured validation of seq_data, ribbon_data and
gene_data so that problems can be found, understood and fixed before
plotting. The result is a "ggchord_validation" object with a
valid flag, errors (severe problems that make the plot
misleading), warnings (drawable but noteworthy issues), per-category
counts, a data summary, the original row numbers of every problem, and a
list of automatically fixable issues.
Usage
validate_ggchord_data(
seq_data,
ribbon_data = NULL,
gene_data = NULL,
strict = FALSE,
check_coordinates = TRUE,
check_duplicates = TRUE,
check_self_links = TRUE,
feature_data = NULL
)
Arguments
seq_data |
data.frame/tibble, required. Basic sequence information
(columns |
ribbon_data |
data.frame/tibble, optional. Alignment results (columns
|
gene_data |
data.frame/tibble, optional. Gene annotation data (columns
|
strict |
Logical. When |
check_coordinates |
Logical, default |
check_duplicates |
Logical, default |
check_self_links |
Logical, default |
feature_data |
Unified annotation table, mutually exclusive with
|
Value
A "ggchord_validation" object (a list) with at least:
validLogical:
TRUEwhen there are no severe errors.errorsdata.frame of severe issues (table, category, row, column, message).
warningsdata.frame of non-severe issues (same columns).
summaryPer-category counts (table, category, severity, n).
data_summaryCounts of sequences/ribbons/genes, unknown IDs, out-of-range rows, etc.
invalid_rowsNamed list of original row numbers per problem category.
cleanabledata.frame of fixable issues with suggested actions.
print() and summary() methods are provided.
See Also
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
data(ribbon_data_example)
links <- ribbon_data_example |>
select(qaccver, saccver, qstart, qend, sstart, send)
data(gene_data_example)
genes <- gene_data_example |>
transmute(accver, start, end, strand = source_strand)
result <- validate_ggchord_data(seqs, links, genes)
result$valid
Validate explicit genome and contig relationships
Description
Checks relational keys without deriving genome membership, changing sequence
order or joining contigs into a continuous sequence. Original input tables
and their metadata are returned unchanged. Sequence lengths and annotation
coordinates can be checked separately with validate_ggchord_data().
Usage
validate_ggchord_hierarchy(seq_data, genomes, strict = FALSE)
Arguments
seq_data |
A data frame containing |
genomes |
A data frame containing a unique |
strict |
Logical. Stop if relational errors are present; warnings about genomes without contigs do not cause failure. |
Details
A sequence belongs to exactly one genome. Sequence accver values must be
globally unique, including when local contig names would be reused by two
genomes. Supply distinct explicit identifiers before validation; this
function never prefixes or rewrites them. Genome rows with no contigs are
reported as warnings, and remain in the returned genome table.
Value
A list with valid, unchanged seq_data and genomes, an issues
data frame (table, row, column, category, severity, message),
and contigs, a genome-order table with genome, n_contigs, and
sequence_rows/accvers list-columns for each valid unique genome key.
See Also
Examples
library(dplyr)
data(seq_data_example)
seqs <- seq_data_example |>
select(accver, length)
contigs <- seqs |>
mutate(genome = accver)
genomes <- tibble(genome = seqs$accver)
validate_ggchord_hierarchy(contigs, genomes)
Preview a ggchord plot at its intended export size
Description
Renders a plot with ggsave() into a temporary PNG or SVG and opens a
small static preview page in the configured IDE viewer or web browser. This
is an export-size preview, not an interactive plot conversion; the original
plot and its standard ggsave() workflow remain unchanged.
ggchord inputs are rendered on a private copy, preserving their layout cache.
See ggchord_layout_contract for the distinct preview/export/diagnostic results.
Automatic height fitting does not resize an overwide legend. If decorations
exceed the requested width, increase width or use, for example,
guides(seq_colour = guide_ggchord_legend(nrow = 2)).
Usage
view_ggchord(
plot = ggplot2::last_plot(),
width = 12.39,
height = 9.71,
units = c("in", "cm", "mm", "px"),
device = c("png", "svg"),
dpi = 144,
bg = NULL,
viewer = c("auto", "ide", "browser", "none")
)
Arguments
plot |
A ggchord or ggplot object, default |
width |
Positive output width. With no explicit dimensions,
|
height |
Positive output height. With no explicit dimensions,
|
units |
Output units: |
device |
Preview device, |
dpi |
Positive raster resolution, default 144. |
bg |
Optional background colour passed to |
viewer |
How to open the preview: |
Value
The normalized temporary image path, invisibly.
RStudio plot pane and export-size rendering
Label packing, guide sizing, and fitted limits use the active graphics
device's physical dimensions. Printing p in a small or narrow
RStudio Plots pane can therefore produce a substantially different layout
from an export, and very small panes may not have enough room for all radial
labels. Resize or Zoom the pane and print again for a larger direct preview.
For size-sensitive chord plots, use view_ggchord() while composing,
then save the final figure with ggsave() at an explicit width and
height matching the intended output. Preview measurements restore the
previously active graphics device.
Examples
library(dplyr)
data(seq_data_example)
p <- ggchord(seq_data_example) +
geom_seq()
if (interactive()) view_ggchord(p)