Title: Modern Network Visualization
Version: 1.5.2
Description: Provides tools for the analysis, visualization, and manipulation of dynamical, social (Saqr et al. (2024) <doi:10.1007/978-3-031-54464-4_10>) and complex networks (Saqr et al. (2025) <doi:10.1145/3706468.3706513>). The package supports multiple network formats and offers flexible tools for heterogeneous, multi-layer, and hierarchical network analysis with simple syntax and extensive toolset.
License: MIT + file LICENSE
URL: https://sonsoles.me/cograph/
BugReports: https://github.com/sonsoleslp/cograph/issues
Depends: R (≥ 4.4.0)
Imports: R6, grid, grDevices, ggplot2, stats, utils
Suggests: igraph, network, scales, testthat (≥ 3.0.0), knitr, rmarkdown, digest, grImport2, rsvg, qgraph, tna, RColorBrewer, colorspace
VignetteBuilder: knitr
Config/testthat/edition: 3
Encoding: UTF-8
RoxygenNote: 7.3.3
NeedsCompilation: no
Packaged: 2026-02-23 22:28:43 UTC; slopezpe
Author: Mohammed Saqr [aut], Sonsoles López-Pernas [aut, cre], Santtu Tikka [aut]
Maintainer: Sonsoles López-Pernas <sonsoles.lopez@uef.fi>
Repository: CRAN
Date/Publication: 2026-03-02 21:40:08 UTC

cograph: Modern Network Visualization

Description

A modern, extensible network visualization package that provides high-quality static and interactive network plots. cograph accepts adjacency matrices, edge lists, or igraph objects and offers customizable layouts, node shapes, edge styles, and themes.

Main Functions

Layouts

cograph provides several built-in layouts:

Themes

Built-in themes include:

Author(s)

Maintainer: Sonsoles López-Pernas sonsoles.lopez@uef.fi

Authors:

See Also

Useful links:


cograph Scaling Constants

Description

Central location for all scaling factors used in splot() and soplot(). These constants are calibrated to produce similar visual output to qgraph when using equivalent parameter values.

Usage

COGRAPH_SCALE

Format

A list with the following elements:

node_factor

Scale factor applied to node_size parameter

node_default

Default node size when not specified

label_default

Default label size (cex multiplier)

label_coupled

Whether label size is coupled to node size

edge_base

Base edge width

edge_scale

Edge width scale factor

edge_default

Default edge width

arrow_factor

Scale factor for arrow sizes

arrow_default

Default arrow size

Details

The default scaling mode uses values calibrated to match qgraph visual appearance:

Legacy mode preserves the original cograph v1.x behavior where:


Legacy Scaling Constants (Pre-v2.0 Behavior)

Description

Scaling constants that preserve the original cograph v1.x behavior. Use scaling = "legacy" to enable these values.

Usage

COGRAPH_SCALE_LEGACY

Format

A list with the same structure as COGRAPH_SCALE


CographLayout R6 Class

Description

Class for managing layout algorithms and computing node positions.

Methods

Public methods


Method new()

Create a new CographLayout object.

Usage
CographLayout$new(type = "circle", ...)
Arguments
type

Layout type (e.g., "circle", "spring", "groups").

...

Additional parameters for the layout algorithm.

Returns

A new CographLayout object.


Method compute()

Compute layout coordinates for a network.

Usage
CographLayout$compute(network, ...)
Arguments
network

A CographNetwork object.

...

Additional parameters passed to the layout function.

Returns

Data frame with x, y coordinates.


Method normalize_coords()

Normalize coordinates to 0-1 range with padding.

Usage
CographLayout$normalize_coords(coords, padding = 0.1)
Arguments
coords

Matrix or data frame with x, y columns.

padding

Numeric. Padding around edges (default 0.1).

Returns

Normalized coordinates.


Method get_type()

Get layout type.

Usage
CographLayout$get_type()
Returns

Character string.


Method get_params()

Get layout parameters.

Usage
CographLayout$get_params()
Returns

List of parameters.


Method print()

Print layout summary.

Usage
CographLayout$print()

Method clone()

The objects of this class are cloneable with this method.

Usage
CographLayout$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

# Create a circular layout
layout <- CographLayout$new("circle")

# Apply to network
adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)
net <- CographNetwork$new(adj)
coords <- layout$compute(net)

CographNetwork R6 Class

Description

Core class representing a network for visualization. Stores nodes, edges, layout coordinates, and aesthetic mappings.

Active bindings

n_nodes

Number of nodes in the network.

n_edges

Number of edges in the network.

is_directed

Whether the network is directed.

has_weights

Whether edges have weights.

node_labels

Vector of node labels.

Methods

Public methods


Method new()

Create a new CographNetwork object.

Usage
CographNetwork$new(input = NULL, directed = NULL, node_labels = NULL)
Arguments
input

Network input (matrix, edge list, or igraph object).

directed

Logical. Force directed interpretation. NULL for auto-detect.

node_labels

Character vector of node labels.

Returns

A new CographNetwork object.


Method clone_network()

Clone the network with optional modifications.

Usage
CographNetwork$clone_network()
Returns

A new CographNetwork object.


Method set_nodes()

Set nodes data frame.

Usage
CographNetwork$set_nodes(nodes)
Arguments
nodes

Data frame with node information.


Method set_edges()

Set edges data frame.

Usage
CographNetwork$set_edges(edges)
Arguments
edges

Data frame with edge information.


Method set_directed()

Set directed flag.

Usage
CographNetwork$set_directed(directed)
Arguments
directed

Logical.


Method set_weights()

Set edge weights.

Usage
CographNetwork$set_weights(weights)
Arguments
weights

Numeric vector of weights.


Method set_layout_coords()

Set layout coordinates.

Usage
CographNetwork$set_layout_coords(coords)
Arguments
coords

Matrix or data frame with x, y columns.


Method set_node_aes()

Set node aesthetics.

Usage
CographNetwork$set_node_aes(aes)
Arguments
aes

List of aesthetic parameters.


Method set_edge_aes()

Set edge aesthetics.

Usage
CographNetwork$set_edge_aes(aes)
Arguments
aes

List of aesthetic parameters.


Method set_theme()

Set theme.

Usage
CographNetwork$set_theme(theme)
Arguments
theme

CographTheme object or theme name.


Method get_nodes()

Get nodes data frame.

Usage
CographNetwork$get_nodes()
Returns

Data frame with node information.


Method get_edges()

Get edges data frame.

Usage
CographNetwork$get_edges()
Returns

Data frame with edge information.


Method get_layout()

Get layout coordinates.

Usage
CographNetwork$get_layout()
Returns

Data frame with x, y coordinates.


Method get_node_aes()

Get node aesthetics.

Usage
CographNetwork$get_node_aes()
Returns

List of node aesthetic parameters.


Method get_edge_aes()

Get edge aesthetics.

Usage
CographNetwork$get_edge_aes()
Returns

List of edge aesthetic parameters.


Method get_theme()

Get theme.

Usage
CographNetwork$get_theme()
Returns

CographTheme object.


Method set_layout_info()

Set layout info.

Usage
CographNetwork$set_layout_info(info)
Arguments
info

List with layout information (name, seed, etc.).


Method get_layout_info()

Get layout info.

Usage
CographNetwork$get_layout_info()
Returns

List with layout information.


Method set_plot_params()

Set plot parameters.

Usage
CographNetwork$set_plot_params(params)
Arguments
params

List of all plot parameters used.


Method get_plot_params()

Get plot parameters.

Usage
CographNetwork$get_plot_params()
Returns

List of plot parameters.


Method print()

Print network summary.

Usage
CographNetwork$print()

Method clone()

The objects of this class are cloneable with this method.

Usage
CographNetwork$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

# Create network from adjacency matrix
adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)
net <- CographNetwork$new(adj)

# Access properties
net$n_nodes
net$n_edges
net$is_directed

CographTheme R6 Class

Description

Class for managing visual themes for network plots.

Active bindings

name

Theme name.

Methods

Public methods


Method new()

Create a new CographTheme object.

Usage
CographTheme$new(
  name = "custom",
  background = "white",
  node_fill = "#4A90D9",
  node_border = "#2C5AA0",
  node_border_width = 1,
  edge_color = "gray50",
  edge_positive_color = "#2E7D32",
  edge_negative_color = "#C62828",
  edge_width = 1,
  label_color = "black",
  label_size = 10,
  title_color = "black",
  title_size = 14,
  legend_background = "white"
)
Arguments
name

Theme name (optional).

background

Background color.

node_fill

Default node fill color.

node_border

Default node border color.

node_border_width

Default node border width.

edge_color

Default edge color.

edge_positive_color

Color for positive edge weights.

edge_negative_color

Color for negative edge weights.

edge_width

Default edge width.

label_color

Default label color.

label_size

Default label size.

title_color

Title color.

title_size

Title size.

legend_background

Legend background color.

Returns

A new CographTheme object.


Method get()

Get a theme parameter.

Usage
CographTheme$get(name)
Arguments
name

Parameter name.

Returns

Parameter value.


Method set()

Set a theme parameter.

Usage
CographTheme$set(name, value)
Arguments
name

Parameter name.

value

Parameter value.


Method get_all()

Get all theme parameters.

Usage
CographTheme$get_all()
Returns

List of parameters.


Method merge()

Merge with another theme.

Usage
CographTheme$merge(other)
Arguments
other

Another CographTheme or list of parameters.

Returns

A new merged CographTheme.


Method clone_theme()

Clone the theme.

Usage
CographTheme$clone_theme()
Returns

A new CographTheme.


Method print()

Print theme summary.

Usage
CographTheme$print()

Method clone()

The objects of this class are cloneable with this method.

Usage
CographTheme$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

# Create a custom theme
theme <- CographTheme$new(
  background = "white",
  node_fill = "steelblue",
  edge_color = "gray60"
)

qgraph Scaling Constants (Exact Values)

Description

Scaling constants that exactly replicate qgraph's visual formulas. Used by splot() for qgraph-compatible network visualization.

Usage

QGRAPH_SCALE

Format

A list with the following elements:

vsize_base

Base multiplier in vsize formula: 8

vsize_decay

Decay constant in vsize formula: 80

vsize_min

Minimum added to vsize: 1

vsize_factor

Scale factor to convert vsize to user coordinates: 0.015

esize_base

Base multiplier in esize formula: 15

esize_decay

Decay constant in esize formula: 90

esize_min

Minimum added to esize: 1

esize_unweighted

Default edge width for unweighted networks: 2

cent2edge_divisor

Divisor in cent2edge formula: 17.5

cent2edge_reference

Reference value in cent2edge: 2.16

cent2edge_plot_ref

Plot reference size: 7

curve_ref_diagonal

Diagonal reference for curve normalization: sqrt(98)

arrow_factor

Arrow size scale factor: 0.04


Edge Aesthetics

Description

Functions for setting edge aesthetic properties.


Node Aesthetics

Description

Functions for setting node aesthetic properties.


Aesthetic Scale Functions

Description

Functions for creating aesthetic scales.


Aggregate Duplicate Edges

Description

Combines duplicate edges by aggregating their weights using a specified function (sum, mean, max, min, or first).

Usage

aggregate_duplicate_edges(edges, method = "mean")

Arguments

edges

Data frame with from, to, and weight columns.

method

Aggregation method: "sum" (default), "mean", "max", "min", "first", or a custom function that takes a numeric vector and returns a single value.

Details

Aggregation Methods

sum

Total weight of all duplicate edges. Useful for frequency counts or when edges represent additive quantities (e.g., number of emails).

mean

Average weight. Useful for averaging multiple measurements or when duplicates represent repeated observations.

max

Maximum weight. Useful for finding the strongest connection or most recent value.

min

Minimum weight. Useful for the most conservative estimate or earliest value.

first

Keep first occurrence. Useful for preserving original order or when duplicates are erroneous.

The output edge list uses canonical node ordering (lower index first for undirected networks), ensuring consistent from/to assignment.

Value

A deduplicated data frame with the same columns as the input, where each node pair appears only once with its aggregated weight.

See Also

detect_duplicate_edges for identifying duplicates before aggregation


Calculate Arrow Base Midpoint

Description

Returns the midpoint between the arrow wings (where the curve should end). This is used to connect the edge line to the back of the arrow head.

Usage

arrow_base_midpoint(x, y, angle, size, arrow_angle = pi/6)

Arguments

x

Arrow tip x coordinate.

y

Arrow tip y coordinate.

angle

Angle of incoming edge (radians).

size

Arrow size in user coordinates.

arrow_angle

Arrow head angle in radians. Default pi/6 (30 degrees).

Value

List with x, y coordinates of the arrow base midpoint.


Calculate Arrow Head Points

Description

Returns the vertices for an arrow head polygon without drawing.

Usage

arrow_head_points(x, y, angle, size, arrow_angle = pi/6)

Arguments

x

Arrow tip x coordinate.

y

Arrow tip y coordinate.

angle

Angle of incoming edge (radians).

size

Arrow size.

arrow_angle

Arrow head angle in radians. Default pi/6 (30 degrees).

Value

List with x, y vectors and midpoint coordinates.


Calculate Arrow Head Points

Description

Calculate Arrow Head Points

Usage

arrow_points(x, y, angle, size, width = 0.5, x_scale = 1, y_scale = 1)

Arguments

x, y

Arrow tip position.

angle

Angle of incoming edge (radians).

size

Arrow size.

width

Arrow width ratio (default 0.5).

x_scale, y_scale

Aspect ratio correction factors.

Value

List with arrow polygon coordinates and midpoint for line connection.


Calculate Arrow Radius

Description

Returns the distance from arrow tip to base midpoint. This is how far back from the tip the arrow extends.

Usage

arrow_radius(size, arrow_angle = pi/6)

Arguments

size

Arrow size in user coordinates.

arrow_angle

Arrow head angle in radians. Default pi/6 (30 degrees).

Value

The arrow radius (distance from tip to base).


Convert to Cograph Network

Description

Creates a lightweight cograph_network object from various network inputs. The resulting object is a named list with all data accessible via $.

Usage

as_cograph(x, directed = NULL, ...)

Arguments

x

Network input. Can be:

  • A square numeric matrix (adjacency/weight matrix)

  • A data frame with edge list (from, to, optional weight columns)

  • An igraph object

  • A statnet network object

  • A qgraph object

  • A tna object

  • An existing cograph_network object (returned as-is)

directed

Logical. Force directed interpretation. NULL for auto-detect.

...

Additional arguments (currently unused).

Details

The cograph_network format is designed to be:

Use getter functions for programmatic access: get_nodes, get_edges, get_labels

Use setter functions to modify: set_nodes, set_edges, set_layout

Value

A cograph_network object: a named list with components:

from

Integer vector of source node indices

to

Integer vector of target node indices

weight

Numeric vector of edge weights

nodes

Data frame with id, label, (x, y if layout applied)

directed

Logical indicating if network is directed

n_nodes

Integer count of nodes

n_edges

Integer count of edges

labels

Character vector of node labels

source

Character indicating input type

layout

Layout coordinates (NULL until computed)

layout_info

Layout algorithm info (NULL until computed)

See Also

get_nodes to extract the nodes data frame, get_edges to extract edges as a data frame, n_nodes and n_edges for counts, is_directed to check directedness, splot for plotting

Examples

# From adjacency matrix
mat <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)
net <- as_cograph(mat)

# Direct $ access to all data
net$from       # edge sources
net$to         # edge targets
net$weight     # edge weights
net$nodes      # nodes data frame
net$directed   # TRUE/FALSE
net$n_nodes    # 3
net$n_edges    # 3

# Getter functions (recommended for programmatic use)
get_nodes(net)   # nodes data frame
get_edges(net)   # edges data frame (from, to, weight)
get_labels(net)  # character vector of labels
n_nodes(net)     # 3
n_edges(net)     # 3
is_directed(net) # FALSE (symmetric matrix)

# Setter functions
net <- set_nodes(net, data.frame(id = 1:3, label = c("A", "B", "C")))
net <- set_edges(net, data.frame(from = c(1,2), to = c(2,3), weight = c(0.5, 0.8)))
net <- set_layout(net, data.frame(x = c(0, 1, 0.5), y = c(0, 0, 1)))

# Plot it
splot(net)

# From igraph (if installed)
if (requireNamespace("igraph", quietly = TRUE)) {
  library(igraph)
  g <- make_ring(10)
  net <- as_cograph(g)
  splot(net)
}

Create cograph_network S3 class wrapper

Description

Create cograph_network S3 class wrapper

Usage

as_cograph_network(network)

Arguments

network

CographNetwork R6 object.

Value

Object with cograph_network class.


Aspect-Corrected atan2

Description

Calculate angle accounting for aspect ratio differences.

Usage

atan2_usr(dy, dx)

Arguments

dy

Change in y (user coordinates).

dx

Change in x (user coordinates).

Value

Angle in radians.


Calculate Bezier Curve Points

Description

Calculate points along a quadratic Bezier curve.

Usage

bezier_points(x0, y0, x1, y1, x2, y2, n = 50)

Arguments

x0, y0

Start point.

x1, y1

Control point.

x2, y2

End point.

n

Number of points to generate.

Value

Data frame with x, y coordinates.


Generate Brain Vertices

Description

Generate Brain Vertices

Usage

brain_vertices(x, y, r, n = 80)

Arguments

x

Center x coordinate.

y

Center y coordinate.

r

Radius.

n

Number of vertices.

Value

List with x, y vectors of vertices.


Build Edge Labels from Template

Description

Generates edge labels for all edges using template formatting.

Usage

build_edge_labels_from_template(
  template = NULL,
  style = "none",
  weights = NULL,
  ci_lower = NULL,
  ci_upper = NULL,
  p_values = NULL,
  stars = NULL,
  digits = 2,
  p_digits = 3,
  p_prefix = "p=",
  ci_format = "bracket",
  oneline = TRUE,
  n
)

Arguments

template

Template string or NULL.

style

Style preset (used if template is NULL).

weights

Edge weights/estimates.

ci_lower

Lower CI bounds (vector).

ci_upper

Upper CI bounds (vector).

p_values

P-values (vector).

stars

Stars input (character vector, logical, or numeric p-values).

digits

Decimal places for estimates.

p_digits

Decimal places for p-values.

p_prefix

Prefix for p-values.

ci_format

CI format: "bracket" or "dash".

oneline

Logical: single line format.

n

Number of edges.

Value

Character vector of formatted labels.


Calculate Point on Node Boundary

Description

Given a node center, size, and angle, calculates the point on the node boundary. Works with various shapes.

Usage

cent_to_edge(x, y, angle, cex, cex2 = NULL, shape = "circle")

Arguments

x

Node center x coordinate.

y

Node center y coordinate.

angle

Angle in radians.

cex

Node size (radius in user coordinates).

cex2

Secondary size for ellipse width (NULL for square aspect).

shape

Node shape: "circle", "square", "ellipse", or polygon name.

Value

List with x, y coordinates on boundary.


Generate Circle Vertices

Description

Generate Circle Vertices

Usage

circle_vertices(x, y, r, n = 50)

Arguments

x

Center x coordinate.

y

Center y coordinate.

r

Radius.

n

Number of vertices.

Value

List with x, y vectors of vertices.


Generate Cloud Vertices

Description

Generate Cloud Vertices

Usage

cloud_vertices(x, y, r, n = 100)

Arguments

x

Center x coordinate.

y

Center y coordinate.

r

Radius.

n

Number of vertices.

Value

List with x, y vectors of vertices.


Create a Network Visualization

Description

The main entry point for cograph. Accepts adjacency matrices, edge lists, igraph, statnet network, qgraph, or tna objects and creates a visualization-ready network object.

Usage

cograph(
  input,
  layout = "spring",
  directed = NULL,
  node_labels = NULL,
  seed = 42,
  ...
)

Arguments

input

Network input. Can be:

  • A square numeric matrix (adjacency/weight matrix)

  • A data frame with edge list (from, to, optional weight columns)

  • An igraph object

  • A statnet network object

  • A qgraph object

  • A tna object

layout

Layout algorithm: "circle", "spring", "groups", "grid", "random", "star", "bipartite", or "custom". Default "spring".

directed

Logical. Force directed interpretation. NULL for auto-detect.

node_labels

Character vector of node labels.

seed

Random seed for deterministic layouts. Default 42. Set NULL for random.

...

Additional arguments passed to the layout function.

Value

A cograph_network object that can be further customized and rendered.

See Also

splot for base R graphics rendering, soplot for grid graphics rendering, sn_nodes for node customization, sn_edges for edge customization, sn_layout for changing layouts, sn_theme for visual themes, sn_palette for color palettes, from_qgraph and from_tna for converting external objects

Examples

# From adjacency matrix
adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)
cograph(adj)

# From edge list
edges <- data.frame(from = c(1, 1, 2), to = c(2, 3, 3))
cograph(edges)

# With customization (pipe-friendly workflow)
adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)
cograph(adj, layout = "circle") |>
  sn_nodes(fill = "steelblue") |>
  sn_edges(color = "gray50") |>
  splot()

# Weighted network with automatic styling
w_adj <- matrix(c(0, 0.5, -0.3, 0.5, 0, 0.4, -0.3, 0.4, 0), nrow = 3)
cograph(w_adj) |>
  sn_edges(color = "weight", width = "weight") |>
  splot()

# With igraph (if installed)
if (requireNamespace("igraph", quietly = TRUE)) {
  library(igraph)
  g <- make_ring(10)
  cograph(g) |> splot()
}

Main Entry Point

Description

The primary function for creating network visualizations.


Compute Adaptive Base Edge Size

Description

Calculates the maximum edge width that decreases with more nodes. Inspired by qgraph but scaled for line widths (not pixels).

Usage

compute_adaptive_esize(n_nodes, directed = FALSE)

Arguments

n_nodes

Number of nodes in the network.

directed

Whether the network is directed (directed networks use thinner edges).

Details

The formula produces reasonable line widths:

For directed networks, the size is reduced by 30% (minimum 1).

Value

Numeric maximum edge width (suitable for lwd parameter).


Compute Circular Layout

Description

Positions nodes along arcs of a circle, with each group occupying one arc. Groups are separated by gaps controlled by angle_spacing.

Usage

compute_circular_layout(
  node_list,
  lab,
  group_indices,
  n_groups,
  angle_spacing = 0.15
)

Arguments

node_list

List of n character vectors.

lab

Node labels from model.

group_indices

List of index vectors for each group.

n_groups

Number of groups.

angle_spacing

Gap between groups as fraction of arc (0-1). Default 0.15.

Value

List with x and y position vectors.


Compute Connectivity-Based Jitter (Horizontal Layout)

Description

For horizontal layouts (left/right columns). Nodes with more cross-group connections are jittered horizontally toward center.

Usage

compute_connectivity_jitter_horizontal(
  weights,
  g1_idx,
  g2_idx,
  amount = 0.8,
  side = "group1"
)

Arguments

weights

Weight matrix.

g1_idx

Indices of group 1 nodes.

g2_idx

Indices of group 2 nodes.

amount

Maximum jitter amount. Default 0.8.

side

Which group(s) to jitter: "group1", "group2", or "both".

Value

Numeric vector of x-offsets for each node.


Compute Connectivity-Based Jitter (Vertical Layout)

Description

For vertical layouts (top/bottom rows). Nodes with more cross-group connections are jittered vertically toward center.

Usage

compute_connectivity_jitter_vertical(
  weights,
  g1_idx,
  g2_idx,
  amount = 0.8,
  side = "group1"
)

Arguments

weights

Weight matrix.

g1_idx

Indices of group 1 nodes (top).

g2_idx

Indices of group 2 nodes (bottom).

amount

Maximum jitter amount. Default 0.8.

side

Which group(s) to jitter: "group1", "group2", or "both".

Value

Numeric vector of y-offsets for each node.


Wrapper for Gephi FR Layout (for layout registry)

Description

Wrapper for Gephi FR Layout (for layout registry)

Usage

compute_layout_gephi_fr(
  network,
  area = 10000,
  gravity = 10,
  speed = 1,
  niter = 100,
  ...
)

Arguments

network

A cograph_network object.

area

Area parameter. Default 10000.

gravity

Gravity force. Default 10.0.

speed

Speed parameter. Default 1.0.

niter

Number of iterations. Default 100.

...

Additional arguments (ignored).

Value

Data frame with x, y coordinates.


Compute Polygon Layout

Description

Positions nodes along edges of a regular n-sided polygon. Each group is placed along one edge. Edges are offset outward from vertices to create empty angles at corners.

Usage

compute_polygon_layout(
  node_list,
  lab,
  group_indices,
  n_sides,
  angle_spacing = 0.15
)

Arguments

node_list

List of n character vectors.

lab

Node labels from model.

group_indices

List of index vectors for each group.

n_sides

Number of sides (groups).

angle_spacing

How far to push edges away from vertices (0-1). Default 0.15.

Value

List with x and y position vectors.


Create Edge Data Frame

Description

Create Edge Data Frame

Usage

create_edges_df(from, to, weight = NULL, directed = FALSE)

Arguments

from

Vector of source node indices.

to

Vector of target node indices.

weight

Vector of edge weights.

directed

Logical. Is the network directed?

Value

Data frame with edge information.


Create Grid Grob Tree

Description

Create a complete grid grob tree for the network (without drawing).

Usage

create_grid_grob(network, title = NULL)

Arguments

network

A cograph_network object.

title

Optional plot title.

Value

A grid gTree object.


Create Node Data Frame

Description

Create Node Data Frame

Usage

create_nodes_df(n, labels = NULL, names = NULL)

Arguments

n

Number of nodes.

labels

Optional node labels.

names

Optional node names for legend (defaults to labels).

Value

Data frame with node information.


Generate Cross/Plus Vertices

Description

Generate Cross/Plus Vertices

Usage

cross_vertices(x, y, r, thickness = 0.3)

Arguments

x

Center x coordinate.

y

Center y coordinate.

r

Half-size.

thickness

Arm thickness as ratio of r.

Value

List with x, y vectors of vertices.


Calculate Control Point for Curved Edge

Description

Calculate Control Point for Curved Edge

Usage

curve_control_point(x1, y1, x2, y2, curvature, pivot = 0.5, shape = 0)

Arguments

x1, y1

Start point.

x2, y2

End point.

curvature

Curvature amount (0 = straight line).

pivot

Position along edge (0-1) where control point sits. 0 = near source, 0.5 = middle (default), 1 = near target.

shape

Spline tension affecting curvature intensity (-1 to 1). Negative = sharper curve, Positive = gentler curve. Default 0.

Value

List with x, y coordinates of control point.


Detect Duplicate Edges in Undirected Network

Description

Identifies edges that appear multiple times between the same pair of nodes. For undirected networks, edges A->B and B->A are considered duplicates. For directed networks, only identical from->to pairs are duplicates.

Usage

detect_duplicate_edges(edges)

Arguments

edges

Data frame with from and to columns (and optionally weight).

Details

This function is useful for cleaning network data before visualization. Duplicate edges can arise from:

The function creates canonical keys by sorting node pairs (lower index first), so edges 1->2 and 2->1 map to the same key "1-2" in undirected mode.

Value

A list with two components:

has_duplicates

Logical indicating whether any duplicates were found.

info

A list of duplicate details, where each element contains: nodes (the node pair), count (number of edges), and weights (vector of weights if available).

See Also

aggregate_duplicate_edges for combining duplicates into single edges


Generate Diamond Vertices

Description

Generate Diamond Vertices

Usage

diamond_vertices(x, y, r)

Arguments

x

Center x coordinate.

y

Center y coordinate.

r

Radius (vertex distance from center).

Value

List with x, y vectors of vertices.


Draw Arrow Head

Description

Draws a filled triangular arrow head at the specified position.

Usage

draw_arrow_base(
  x,
  y,
  angle,
  size,
  arrow_angle = pi/6,
  col = "black",
  border = NULL,
  lwd = 1
)

Arguments

x

Arrow tip x coordinate.

y

Arrow tip y coordinate.

angle

Angle of incoming edge (radians).

size

Arrow size in user coordinates.

arrow_angle

Arrow head angle in radians. Default pi/6 (30 degrees).

col

Arrow fill color.

border

Arrow border color (default same as fill).

lwd

Border line width.


Draw Brain Node

Description

Simplified brain outline using overlapping curves.

Usage

draw_brain(x, y, size, fill, border_color, border_width, alpha = 1, ...)

Draw Chip Node

Description

Square with pins extending from all edges (processor/IC chip).

Usage

draw_chip(
  x,
  y,
  size,
  fill,
  border_color,
  border_width,
  alpha = 1,
  pins_per_side = 3,
  ...
)

Arguments

pins_per_side

Number of pins per side.


Draw Chip Node (Base R)

Description

Square with pins extending from all edges.

Usage

draw_chip_node_base(
  x,
  y,
  size,
  col,
  border.col,
  border.width,
  pins_per_side = 3
)

Draw Circle Node

Description

Draw Circle Node

Usage

draw_circle(x, y, size, fill, border_color, border_width, alpha = 1, ...)

Draw Circle Arrow (Dot)

Description

Draws a circular dot at the arrow position (alternative to triangular arrow).

Usage

draw_circle_arrow_base(x, y, size, col = "black", border = NULL)

Arguments

x

Position x coordinate.

y

Position y coordinate.

size

Dot radius.

col

Fill color.

border

Border color.


Draw Cloud Node

Description

Cloud shape (cloud computing).

Usage

draw_cloud(x, y, size, fill, border_color, border_width, alpha = 1, ...)

Draw Cross/Plus Node

Description

Draw Cross/Plus Node

Usage

draw_cross(
  x,
  y,
  size,
  fill,
  border_color,
  border_width,
  alpha = 1,
  thickness = 0.3,
  ...
)

Draw Curve with Optional Start Segment

Description

Draws a curve (as lines) with an optional differently-styled start segment. Used internally to support dashed/dotted start segments for edge direction clarity.

Usage

draw_curve_with_start_segment(
  x,
  y,
  col,
  lwd,
  lty,
  start_lty = 1,
  start_fraction = 0
)

Arguments

x, y

Vectors of curve coordinates.

col

Line color.

lwd

Line width.

lty

Main line type.

start_lty

Line type for start segment.

start_fraction

Fraction of curve for start segment (0-0.5).


Draw Curved Arrow Head

Description

Draws an arrow head at the end of a curved edge, with angle following the curve direction.

Usage

draw_curved_arrow_base(
  spline_x,
  spline_y,
  size,
  arrow_angle = pi/6,
  col = "black",
  border = NULL
)

Arguments

spline_x

X coordinates of the spline.

spline_y

Y coordinates of the spline.

size

Arrow size.

arrow_angle

Arrow head angle in radians. Default pi/6 (30 degrees).

col

Arrow fill color.

border

Arrow border color.


Draw Curved Edge

Description

Draw Curved Edge

Usage

draw_curved_edge(
  x1,
  y1,
  x2,
  y2,
  curvature,
  color,
  width,
  lty,
  show_arrow,
  arrow_size,
  bidirectional = FALSE,
  curve_shape = 0,
  curve_pivot = 0.5,
  x_scale = 1,
  y_scale = 1
)

Draw Curved Edge with xspline (qgraph-style)

Description

Renders a curved edge using xspline() with optional arrow. Uses qgraph-style curve calculation for smooth, natural-looking curves. Curve direction is normalized so positive curve always bends the same visual direction regardless of edge orientation.

Usage

draw_curved_edge_base(
  x1,
  y1,
  x2,
  y2,
  curve = 0.2,
  curvePivot = 0.5,
  col = "gray50",
  lwd = 1,
  lty = 1,
  arrow = TRUE,
  asize = 0.02,
  bidirectional = FALSE,
  start_lty = 1,
  start_fraction = 0,
  arrow_angle = pi/6
)

Arguments

x1, y1

Start point coordinates.

x2, y2

End point coordinates.

curve

Curvature amount (positive = clockwise, negative = counterclockwise when looking from source to target).

curvePivot

Position along edge for control point (0-1).

col

Edge color.

lwd

Line width.

lty

Line type.

arrow

Logical: draw arrow at target?

asize

Arrow size.

bidirectional

Logical: draw arrow at source too?

start_lty

Line type for start segment. 1=solid (default), 2=dashed, 3=dotted.

start_fraction

Fraction of edge length for start segment (0-0.5). Default 0.

arrow_angle

Arrow head angle in radians. Default pi/6 (30 degrees).


Draw Database Node

Description

Cylinder shape (data storage).

Usage

draw_database(x, y, size, fill, border_color, border_width, alpha = 1, ...)

Draw Database Node (Base R)

Description

Cylinder shape.

Usage

draw_database_node_base(x, y, size, col, border.col, border.width)

Draw Diamond Node

Description

Draw Diamond Node

Usage

draw_diamond(x, y, size, fill, border_color, border_width, alpha = 1, ...)

Draw Donut Node

Description

Draw a donut chart node showing a fill proportion (0-1) as an arc. The fill starts from 12 o'clock (top) and fills clockwise.

Usage

draw_donut(
  x,
  y,
  size,
  fill,
  border_color,
  border_width,
  alpha = 1,
  values = NULL,
  colors = NULL,
  inner_ratio = 0.5,
  bg_color = "gray90",
  show_value = TRUE,
  value_size = 8,
  value_color = "black",
  value_fontface = "bold",
  value_fontfamily = "sans",
  value_digits = 2,
  value_prefix = "",
  value_suffix = "",
  value_format = NULL,
  donut_border_width = NULL,
  ...
)

Arguments

x, y

Node center coordinates (NPC units).

size

Node radius (NPC units).

fill

Fill color for the donut ring.

border_color

Border color.

border_width

Border line width.

alpha

Transparency (0-1).

values

Single numeric value (0-1) specifying fill proportion. 0.1 = 10% filled arc, 0.5 = 50% filled, 1.0 = full ring.

colors

Override fill color (optional).

inner_ratio

Ratio of inner to outer radius (0-1). Default 0.5.

bg_color

Background color for unfilled portion. Default "gray90".

show_value

Logical: show value in center? Default FALSE.

value_size

Font size for center value.

value_color

Color for center value text.

value_fontface

Font face for center value.

value_fontfamily

Font family for center value.

value_digits

Decimal places for value display.

value_prefix

Text before value (e.g., "$").

value_suffix

Text after value (e.g., "%").

value_format

Custom format function (overrides digits).

donut_border_width

Border width for donut ring (NULL = use border_width).


Draw Donut Chart Node

Description

Renders a node as a donut chart with an inner hole. The donut shows a fill proportion (0-1) as an arc starting from 12 o'clock.

Usage

draw_donut_node_base(
  x,
  y,
  size,
  values,
  colors = NULL,
  default_color = NULL,
  inner_ratio = 0.5,
  bg_color = "gray90",
  center_color = "white",
  border.col = "black",
  border.width = 1,
  donut_border.width = NULL,
  outer_border.col = NULL,
  border.lty = 1,
  show_value = TRUE,
  value_cex = 0.8,
  value_col = "black",
  value_fontface = "bold",
  value_fontfamily = "sans",
  value_digits = 2,
  value_prefix = "",
  value_suffix = ""
)

Arguments

x, y

Node center coordinates.

size

Outer radius.

values

Single numeric value (0-1) specifying fill proportion. 0.1 = 10% filled arc, 0.5 = 50% filled, 1.0 = full ring.

colors

Fill color for the donut ring.

default_color

Fallback color when colors is NULL.

inner_ratio

Ratio of inner to outer radius (0-1). Default 0.5.

bg_color

Background color for unfilled portion. Default "gray90".

border.col

Border color.

border.width

Border line width.

donut_border.width

Border width for donut ring (NULL = use border.width).

show_value

Logical: show value in center? Default FALSE.

value_cex

Text size for center value.

value_col

Text color for center value.

value_fontface

Font face for center value ("plain", "bold", "italic", "bold.italic").

value_fontfamily

Font family for center value ("sans", "serif", "mono").

value_digits

Decimal places for value display.

value_prefix

Text before value (e.g., "$").

value_suffix

Text after value (e.g., "%").


Draw Donut with Inner Pie Node

Description

Draw a node with an outer donut ring showing a proportion and an inner pie chart with multiple segments.

Usage

draw_donut_pie(
  x,
  y,
  size,
  fill,
  border_color,
  border_width,
  alpha = 1,
  donut_value = NULL,
  pie_values = NULL,
  pie_colors = NULL,
  inner_ratio = 0.5,
  bg_color = "gray90",
  pie_border_width = NULL,
  donut_border_width = NULL,
  ...
)

Arguments

pie_border_width

Border width for pie segments (optional).

donut_border_width

Border width for donut ring (optional).


Draw Donut with Inner Pie

Description

Renders a node with outer donut ring and inner pie chart.

Usage

draw_donut_pie_node_base(
  x,
  y,
  size,
  donut_value = 1,
  donut_color = "#4A90D9",
  pie_values = NULL,
  pie_colors = NULL,
  pie_default_color = NULL,
  inner_ratio = 0.5,
  bg_color = "gray90",
  border.col = "black",
  border.width = 1,
  pie_border.width = NULL,
  donut_border.width = NULL
)

Arguments

x, y

Node center coordinates.

size

Outer radius.

donut_value

Single value (0-1) for donut progress.

donut_color

Fill color for donut ring.

pie_values

Numeric vector for pie segments.

pie_colors

Vector of colors for pie segments.

pie_default_color

Default color for pie when pie_colors is NULL.

inner_ratio

Ratio of inner to outer radius.

bg_color

Background color.

border.col

Border color.

border.width

Border line width.

pie_border.width

Border width for pie slice dividers (NULL = use border.width * 0.5).

donut_border.width

Border width for donut ring (NULL = use border.width).


Draw Double Donut with Inner Pie Node

Description

Draw a node with two concentric donut rings and an optional inner pie chart. From outside to inside: outer donut ring, inner donut ring, center pie.

Usage

draw_double_donut_pie(
  x,
  y,
  size,
  fill,
  border_color,
  border_width,
  alpha = 1,
  donut_values = NULL,
  donut_colors = NULL,
  donut2_values = NULL,
  donut2_colors = NULL,
  pie_values = NULL,
  pie_colors = NULL,
  outer_inner_ratio = 0.7,
  inner_inner_ratio = 0.4,
  bg_color = "gray90",
  pie_border_width = NULL,
  donut_border_width = NULL,
  ...
)

Arguments

pie_border_width

Border width for pie segments (optional).

donut_border_width

Border width for donut rings (optional).


Draw Double Donut with Inner Pie

Description

Renders a node with two concentric donut rings and an optional inner pie chart. From outside to inside: outer donut ring, inner donut ring, center pie.

Usage

draw_double_donut_pie_node_base(
  x,
  y,
  size,
  donut_values = NULL,
  donut_colors = NULL,
  donut2_values = NULL,
  donut2_colors = NULL,
  pie_values = NULL,
  pie_colors = NULL,
  pie_default_color = NULL,
  outer_inner_ratio = 0.7,
  inner_inner_ratio = 0.4,
  bg_color = "gray90",
  border.col = "black",
  border.width = 1,
  pie_border.width = NULL,
  donut_border.width = NULL
)

Arguments

x, y

Node center coordinates.

size

Outer radius.

donut_values

Values for outer donut ring (vector for segments, or single 0-1 for progress).

donut_colors

Colors for outer donut segments.

donut2_values

Values for inner donut ring (vector for segments, or single 0-1 for progress).

donut2_colors

Colors for inner donut segments.

pie_values

Numeric vector for center pie segments.

pie_colors

Vector of colors for pie segments.

pie_default_color

Default color for pie when pie_colors is NULL.

outer_inner_ratio

Where outer donut ends (inner radius as ratio of outer radius). Default 0.7.

inner_inner_ratio

Where inner donut ends (inner radius as ratio of outer radius). Default 0.4.

bg_color

Background color for unfilled portions.

border.col

Border color.

border.width

Border line width.

pie_border.width

Border width for pie slice dividers.

donut_border.width

Border width for donut rings.


Draw Edge Label

Description

Renders a label on an edge.

Usage

draw_edge_label_base(
  x,
  y,
  label,
  cex = 0.8,
  col = "gray30",
  bg = "white",
  font = 1,
  shadow = FALSE,
  shadow_color = "gray40",
  shadow_offset = 0.5,
  shadow_alpha = 0.5
)

Arguments

x, y

Label position coordinates.

label

Text to display.

cex

Character expansion factor.

col

Text color.

bg

Background color (or NA for none).

font

Font face.

shadow

Logical: enable drop shadow?

shadow_color

Shadow color.

shadow_offset

Shadow offset distance.

shadow_alpha

Shadow transparency.


Draw Ellipse Node

Description

Draw Ellipse Node

Usage

draw_ellipse(
  x,
  y,
  size,
  fill,
  border_color,
  border_width,
  alpha = 1,
  aspect = 0.6,
  ...
)

Draw Gear Node

Description

Gear/cog shape (processing/automation).

Usage

draw_gear(
  x,
  y,
  size,
  fill,
  border_color,
  border_width,
  alpha = 1,
  n_teeth = 8,
  ...
)

Arguments

n_teeth

Number of gear teeth.


Draw Heart Node

Description

Draw Heart Node

Usage

draw_heart(x, y, size, fill, border_color, border_width, alpha = 1, ...)

Draw Hexagon Node

Description

Draw Hexagon Node

Usage

draw_hexagon(x, y, size, fill, border_color, border_width, alpha = 1, ...)

Draw Network Node

Description

Interconnected nodes pattern (mini network inside).

Usage

draw_network(x, y, size, fill, border_color, border_width, alpha = 1, ...)

Draw Network Node (Base R)

Description

Interconnected nodes pattern.

Usage

draw_network_node_base(x, y, size, col, border.col, border.width)

Draw Neural Node

Description

Circle with small connection circles around the perimeter (neuron-like).

Usage

draw_neural(
  x,
  y,
  size,
  fill,
  border_color,
  border_width,
  alpha = 1,
  n_connections = 6,
  ...
)

Arguments

n_connections

Number of connection points around perimeter.


Draw Neural Node (Base R)

Description

Circle with small connection circles around perimeter.

Usage

draw_neural_node_base(
  x,
  y,
  size,
  col,
  border.col,
  border.width,
  n_connections = 6
)

Draw a Single Node

Description

Renders a node at the specified position with given aesthetics.

Usage

draw_node_base(
  x,
  y,
  size,
  size2 = NULL,
  shape = "circle",
  col = "#4A90D9",
  border.col = "#2C5AA0",
  border.width = 1,
  ...
)

Arguments

x, y

Node center coordinates.

size

Node radius in user coordinates.

size2

Secondary size (for ellipse height).

shape

Node shape name.

col

Fill color.

border.col

Border color.

border.width

Border line width.

...

Additional parameters.


Draw Node Label

Description

Renders a text label at or near a node.

Usage

draw_node_label_base(
  x,
  y,
  label,
  cex = 1,
  col = "black",
  font = 1,
  family = "sans",
  hjust = 0.5,
  vjust = 0.5,
  srt = 0,
  pos = NULL,
  offset = 0.5
)

Arguments

x, y

Label position coordinates.

label

Text to display.

cex

Character expansion factor.

col

Text color.

font

Font face (1=plain, 2=bold, 3=italic, 4=bold italic).

family

Font family ("sans", "serif", "mono").

hjust

Horizontal justification (0=left, 0.5=center, 1=right).

vjust

Vertical justification (0=bottom, 0.5=center, 1=top).

srt

String rotation angle in degrees.

pos

Position relative to point (NULL=centered, 1=below, 2=left, 3=above, 4=right).

offset

Offset distance when using pos.


Draw Open Arrow Head

Description

Draws an open (unfilled) V-shaped arrow head.

Usage

draw_open_arrow_base(
  x,
  y,
  angle,
  size,
  arrow_angle = pi/6,
  col = "black",
  lwd = 1
)

Arguments

x

Arrow tip x coordinate.

y

Arrow tip y coordinate.

angle

Angle of incoming edge (radians).

size

Arrow size.

arrow_angle

Arrow head angle in radians. Default pi/6 (30 degrees).

col

Arrow color.

lwd

Line width.


Draw Pentagon Node

Description

Draw Pentagon Node

Usage

draw_pentagon(x, y, size, fill, border_color, border_width, alpha = 1, ...)

Draw Pie Node

Description

Draw a pie chart node with multiple segments.

Usage

draw_pie(
  x,
  y,
  size,
  fill,
  border_color,
  border_width,
  alpha = 1,
  values = NULL,
  colors = NULL,
  pie_border_width = NULL,
  default_color = NULL,
  ...
)

Arguments

pie_border_width

Border width for pie segments (optional, defaults to border_width * 0.5).

default_color

Fallback color when colors is NULL and there's a single segment.


Draw Pie Chart Node

Description

Renders a node as a pie chart with multiple colored segments. The pie is drawn slightly inside the node boundary to leave room for arrows.

Usage

draw_pie_node_base(
  x,
  y,
  size,
  values,
  colors = NULL,
  default_color = NULL,
  border.col = "black",
  border.width = 1,
  pie_border.width = NULL
)

Arguments

x, y

Node center coordinates.

size

Node radius.

values

Numeric vector of values (will be normalized to proportions).

colors

Vector of colors for each segment.

default_color

Fallback color when colors is NULL and values length is 1.

border.col

Border color.

border.width

Border line width.

pie_border.width

Border width for pie slice dividers (NULL = use border.width).


Draw Polygon Donut Node

Description

Draws a donut ring on a polygon shape where segments follow polygon edges. The fill shows a proportion (0-1) as filled segments starting from the top vertex.

Usage

draw_polygon_donut(
  x,
  y,
  size,
  fill,
  border_color,
  border_width,
  alpha = 1,
  values = NULL,
  colors = NULL,
  inner_ratio = 0.5,
  bg_color = "gray90",
  donut_shape = "square",
  show_value = TRUE,
  value_size = 8,
  value_color = "black",
  value_fontface = "bold",
  value_fontfamily = "sans",
  value_digits = 2,
  value_prefix = "",
  value_suffix = "",
  value_format = NULL,
  donut_border_width = NULL,
  ...
)

Arguments

x, y

Node center coordinates (NPC units).

size

Node radius (NPC units).

fill

Fill color for the donut ring.

border_color

Border color.

border_width

Border line width.

alpha

Transparency (0-1).

values

Single numeric value (0-1) specifying fill proportion. 0.1 = 10% filled, 0.5 = 50% filled, 1.0 = full ring.

colors

Override fill color (optional).

inner_ratio

Ratio of inner to outer radius (0-1). Default 0.5.

bg_color

Background color for unfilled portion. Default "gray90".

donut_shape

Base polygon shape: "circle", "square", "hexagon", "triangle", "diamond", "pentagon".

show_value

Logical: show value in center? Default FALSE.

value_size

Font size for center value.

value_color

Color for center value text.

value_fontface

Font face for center value.

value_fontfamily

Font family for center value.

value_digits

Decimal places for value display.

value_prefix

Text before value.

value_suffix

Text after value.

value_format

Custom format function.

donut_border_width

Border width for donut ring (NULL = use border_width).


Draw Polygon Donut Node (Base R)

Description

Renders a donut on a polygon shape where segments follow polygon edges. The donut shows a fill proportion (0-1) as filled segments starting from the top.

Usage

draw_polygon_donut_node_base(
  x,
  y,
  size,
  values,
  colors = NULL,
  default_color = NULL,
  inner_ratio = 0.5,
  bg_color = "gray90",
  center_color = "white",
  donut_shape = "square",
  border.col = "black",
  border.width = 1,
  donut_border.width = NULL,
  outer_border.col = NULL,
  border.lty = 1,
  show_value = TRUE,
  value_cex = 0.8,
  value_col = "black",
  value_fontface = "bold",
  value_fontfamily = "sans",
  value_digits = 2,
  value_prefix = "",
  value_suffix = ""
)

Arguments

x, y

Node center coordinates.

size

Outer radius.

values

Single numeric value (0-1) specifying fill proportion. 0.1 = 10% filled, 0.5 = 50% filled, 1.0 = full ring.

colors

Fill color for the donut ring.

default_color

Fallback color when colors is NULL.

inner_ratio

Ratio of inner to outer radius (0-1). Default 0.5.

bg_color

Background color for unfilled portion. Default "gray90".

donut_shape

Base polygon shape: "square", "hexagon", "triangle", etc.

border.col

Border color.

border.width

Border line width.

donut_border.width

Border width for donut ring (NULL = use border.width).

show_value

Logical: show value in center? Default FALSE.

value_cex

Text size for center value.

value_col

Text color for center value.

value_fontface

Font face for center value.

value_fontfamily

Font family for center value.

value_digits

Decimal places for value display.

value_prefix

Text before value (e.g., "$").

value_suffix

Text after value (e.g., "%").


Draw Robot Node

Description

Rounded square with antenna and eyes (robot head).

Usage

draw_robot(x, y, size, fill, border_color, border_width, alpha = 1, ...)

Draw Robot Node (Base R)

Description

Rounded square with antenna and eyes.

Usage

draw_robot_node_base(x, y, size, col, border.col, border.width)

Draw Self-Loop

Description

Draw Self-Loop

Usage

draw_self_loop(x, y, node_size, color, width, lty, rotation = pi/2)

Arguments

x, y

Node center coordinates.

node_size

Node radius.

color

Loop color.

width

Loop line width.

lty

Loop line type.

rotation

Angle in radians for loop direction (default: pi/2 = top).


Draw Self-Loop Edge (qgraph-style)

Description

Renders a self-loop (edge from node to itself) using a teardrop/circular loop shape similar to qgraph.

Usage

draw_self_loop_base(
  x,
  y,
  node_size,
  col = "gray50",
  lwd = 1,
  lty = 1,
  rotation = pi/2,
  arrow = TRUE,
  asize = 0.02,
  arrow_angle = pi/6
)

Arguments

x, y

Node center coordinates.

node_size

Node radius.

col

Loop color.

lwd

Line width.

lty

Line type.

rotation

Angle in radians for loop direction (default: pi/2 = top).

arrow

Logical: draw arrow?

asize

Arrow size.

arrow_angle

Arrow head angle in radians. Default pi/6 (30 degrees).


Draw Square Node

Description

Draw Square Node

Usage

draw_square(x, y, size, fill, border_color, border_width, alpha = 1, ...)

Draw Star Node

Description

Draw Star Node

Usage

draw_star(
  x,
  y,
  size,
  fill,
  border_color,
  border_width,
  alpha = 1,
  n_points = 5,
  inner_ratio = 0.4,
  ...
)

Draw Straight Edge

Description

Draw Straight Edge

Usage

draw_straight_edge(
  x1,
  y1,
  x2,
  y2,
  color,
  width,
  lty,
  show_arrow,
  arrow_size,
  bidirectional = FALSE,
  x_scale = 1,
  y_scale = 1
)

Draw Straight Edge

Description

Renders a straight edge between two points with optional arrow.

Usage

draw_straight_edge_base(
  x1,
  y1,
  x2,
  y2,
  col = "gray50",
  lwd = 1,
  lty = 1,
  arrow = TRUE,
  asize = 0.02,
  bidirectional = FALSE,
  start_lty = 1,
  start_fraction = 0,
  arrow_angle = pi/6
)

Arguments

x1, y1

Start point coordinates.

x2, y2

End point coordinates.

col

Edge color.

lwd

Line width.

lty

Line type.

arrow

Logical: draw arrow at target?

asize

Arrow size.

bidirectional

Logical: draw arrow at source too?

start_lty

Line type for start segment. 1=solid (default), 2=dashed, 3=dotted.

start_fraction

Fraction of edge length for start segment (0-0.5). Default 0.

arrow_angle

Arrow head angle in radians. Default pi/6 (30 degrees).


Draw SVG Shape (Grid)

Description

Render an SVG as a node shape using grid graphics.

Usage

draw_svg_shape(
  x,
  y,
  size,
  svg_data,
  fill,
  border_color,
  border_width,
  alpha = 1,
  preserve_aspect = TRUE
)

Arguments

x, y

Node center coordinates (NPC units).

size

Node size (NPC units).

svg_data

SVG data list from registry.

fill

Fill color (replaces SVG fill colors).

border_color

Border color.

border_width

Border width.

alpha

Transparency.

preserve_aspect

Maintain SVG aspect ratio.

Value

Grid grob or nullGrob if SVG unavailable.


Draw SVG Shape (Base R)

Description

Render an SVG as a node shape using base R graphics. Falls back to circle if rasterization fails.

Usage

draw_svg_shape_base(x, y, size, svg_data, fill, border_color, border_width)

Arguments

x, y

Node center coordinates.

size

Node size.

svg_data

SVG data list from registry.

fill

Fill color.

border_color

Border color.

border_width

Border width.


Draw Triangle Node

Description

Draw Triangle Node

Usage

draw_triangle(x, y, size, fill, border_color, border_width, alpha = 1, ...)

Calculate Edge Endpoint on Node Border

Description

Calculates the point where an edge should meet the node border. Uses plain NPC units to match circleGrob borders.

Usage

edge_endpoint(
  node_x,
  node_y,
  other_x,
  other_y,
  node_size,
  shape = "circle",
  x_scale = 1,
  y_scale = 1
)

Arguments

node_x, node_y

Node center in npc.

other_x, other_y

Other endpoint in npc.

node_size

Node radius in npc units.

shape

Node shape.

x_scale, y_scale

Aspect ratio correction factors.

Value

List with x, y coordinates in npc.


Generate Ellipse Vertices

Description

Generate Ellipse Vertices

Usage

ellipse_vertices(x, y, rx, ry, n = 50)

Arguments

x

Center x coordinate.

y

Center y coordinate.

rx

Horizontal radius.

ry

Vertical radius.

n

Number of vertices.

Value

List with x, y vectors of vertices.


Expand Parameter to Length (Strict)

Description

Expands a parameter to length n. Only accepts length 1 or length n. Throws error for any other length (no silent recycling).

Usage

expand_param(x, n, name = "parameter")

Arguments

x

Value to expand.

n

Target length.

name

Parameter name for error message.

Value

Vector of length n.


Filter Edges by Weight Threshold

Description

Removes edges below the minimum weight threshold.

Usage

filter_edges_by_weight(edges, minimum = 0)

Arguments

edges

Edge data frame.

minimum

Minimum absolute weight to include.

Value

Filtered edge data frame.


Find Split Index for Curve Based on Arc Length Fraction

Description

Calculates the index at which to split a curve's coordinate arrays so that the first segment covers a given fraction of the total arc length.

Usage

find_curve_split_index(x, y, fraction)

Arguments

x, y

Vectors of curve coordinates.

fraction

Desired fraction of total arc length (0-1).

Value

Index at which to split the arrays.


Convert Fontface String to Numeric

Description

Converts fontface string specification to numeric value used by R graphics. Handles both string ("plain", "bold", "italic", "bold.italic") and numeric (1, 2, 3, 4) inputs for backwards compatibility.

Usage

fontface_to_numeric(fontface)

Arguments

fontface

Character or numeric fontface specification.

Value

Numeric fontface value (1=plain, 2=bold, 3=italic, 4=bold.italic).


Convert Numeric Fontface to String

Description

Converts numeric fontface value to string specification. Handles both numeric (1, 2, 3, 4) and string inputs.

Usage

fontface_to_string(fontface)

Arguments

fontface

Numeric or character fontface specification.

Value

Character fontface value ("plain", "bold", "italic", "bold.italic").


Format CI Range

Description

Formats confidence interval bounds as a range string.

Usage

format_ci_range(lower, upper, digits = 2, format = "bracket")

Arguments

lower

Lower bound.

upper

Upper bound.

digits

Number of decimal places.

format

CI format: "bracket" for ⁠[low, up]⁠ or "dash" for low-up.

Value

Formatted CI range string.


Format Edge Label from Template

Description

Processes a template string with placeholders and substitutes values.

Usage

format_edge_label_template(
  template,
  weight = NA,
  ci_lower = NA,
  ci_upper = NA,
  p_value = NA,
  stars = "",
  digits = 2,
  p_digits = 3,
  p_prefix = "p=",
  ci_format = "bracket",
  oneline = TRUE
)

Arguments

template

Template string with placeholders: {est}, {range}, {low}, {up}, {p}, {stars}.

weight

Edge weight (estimate).

ci_lower

Lower CI bound.

ci_upper

Upper CI bound.

p_value

P-value.

stars

Significance stars string.

digits

Decimal places for estimates.

p_digits

Decimal places for p-values.

p_prefix

Prefix for p-values.

ci_format

CI format: "bracket" or "dash".

oneline

Logical: single line format (space-separated) or multiline.

Value

Formatted label string.


Format P-value

Description

Formats a p-value with specified decimal places and prefix.

Usage

format_pvalue(p, digits = 3, prefix = "p=")

Arguments

p

Numeric p-value.

digits

Number of decimal places.

prefix

Prefix string (e.g., "p=").

Value

Formatted p-value string.


Convert a qgraph object to cograph parameters

Description

Extracts the network, layout, and all relevant arguments from a qgraph object and passes them to a cograph plotting engine. Reads resolved values from graphAttributes rather than raw Arguments.

Usage

from_qgraph(
  qgraph_object,
  engine = c("splot", "soplot"),
  plot = TRUE,
  weight_digits = 2,
  show_zero_edges = FALSE,
  ...
)

Arguments

qgraph_object

Return value of qgraph::qgraph()

engine

Which cograph renderer to use: "splot" or "soplot". Default: "splot".

plot

Logical. If TRUE (default), immediately plot using the chosen engine.

weight_digits

Number of decimal places to round edge weights to. Default 2. Edges that round to zero are removed unless show_zero_edges = TRUE.

show_zero_edges

Logical. If TRUE, keep edges even if their weight rounds to zero. Default: FALSE.

...

Override any extracted parameter. Use qgraph-style names (e.g., minimum) or cograph names (e.g., threshold).

Details

Parameter Mapping

The following qgraph parameters are automatically extracted and mapped to cograph equivalents:

Node properties:

Edge properties:

Graph properties:

Pie/Donut:

Important Notes

Value

Invisibly, a named list of cograph parameters that can be passed to splot() or soplot().

See Also

cograph for creating networks from scratch, splot and soplot for plotting engines, from_tna for tna object conversion

Examples

# Convert and plot a qgraph object
if (requireNamespace("qgraph", quietly = TRUE)) {
  library(qgraph)
  adj <- matrix(c(0, .5, .3, .5, 0, .4, .3, .4, 0), 3, 3)
  q <- qgraph(adj)
  from_qgraph(q)  # Plots with splot

  # Use soplot engine instead
  from_qgraph(q, engine = "soplot")

  # Override extracted parameters
  from_qgraph(q, node_fill = "steelblue", layout = "circle")

  # Extract parameters without plotting
  params <- from_qgraph(q, plot = FALSE)
  names(params)  # See what was extracted

  # Works with themed qgraph objects
  q_themed <- qgraph(adj, theme = "colorblind", posCol = "blue")
  from_qgraph(q_themed)
}


Convert a tna object to cograph parameters

Description

Extracts the transition matrix, labels, and initial state probabilities from a tna object and plots with cograph. Initial probabilities are mapped to donut fills.

Usage

from_tna(
  tna_object,
  engine = c("splot", "soplot"),
  plot = TRUE,
  weight_digits = 2,
  show_zero_edges = FALSE,
  ...
)

Arguments

tna_object

A tna object from tna::tna()

engine

Which cograph renderer to use: "splot" or "soplot". Default: "splot".

plot

Logical. If TRUE (default), immediately plot using the chosen engine.

weight_digits

Number of decimal places to round edge weights to. Default 2. Edges that round to zero are removed unless show_zero_edges = TRUE.

show_zero_edges

Logical. If TRUE, keep edges even if their weight rounds to zero. Default: FALSE.

...

Additional parameters passed to the plotting engine (e.g., layout, node_fill, donut_color).

Details

Conversion Process

The tna object's transition matrix becomes edge weights, labels become node labels, and initial state probabilities (inits) are mapped to donut_fill values to visualize starting state distributions.

TNA networks are always treated as directed because transition matrices represent directional state changes.

The default donut_inner_ratio of 0.8 creates thin rings that effectively visualize probability values without obscuring node labels.

Parameter Mapping

The following tna properties are automatically extracted:

TNA Visual Defaults

The following visual defaults are applied for TNA plots (all can be overridden via ...):

Value

Invisibly, a named list of cograph parameters that can be passed to splot() or soplot().

See Also

cograph for creating networks from scratch, splot and soplot for plotting engines, from_qgraph for qgraph object conversion

Examples

# Convert and plot a tna object
if (requireNamespace("tna", quietly = TRUE)) {
  library(tna)
  trans <- tna(group_regulation)
  from_tna(trans)  # Plots with donut rings showing initial probabilities

  # Use soplot engine instead
  from_tna(trans, engine = "soplot")

  # Customize the visualization
  from_tna(trans, layout = "circle", donut_color = c("steelblue", "gray90"))

  # Extract parameters without plotting
  params <- from_tna(trans, plot = FALSE)
  # Modify and plot manually
  params$node_fill <- "coral"
  do.call(splot, params)
}


Generate Gear Vertices

Description

Generate Gear Vertices

Usage

gear_vertices(x, y, r, n_teeth = 8)

Arguments

x

Center x coordinate.

y

Center y coordinate.

r

Outer radius.

n_teeth

Number of teeth.

Value

List with x, y vectors of vertices.


Get Polygon Vertices by Shape Name

Description

Returns outer polygon vertices for donut ring shapes.

Usage

get_donut_base_vertices(shape, x, y, r)

Arguments

shape

Shape name.

x

Center x coordinate.

y

Center y coordinate.

r

Radius/size.

Value

List with x, y vectors of vertices.


Get Label Position on Edge

Description

Calculates the position for an edge label (matches qgraph-style curves). For curved edges, the label is offset perpendicular to the edge to avoid overlapping with the edge line.

Usage

get_edge_label_position(
  x1,
  y1,
  x2,
  y2,
  position = 0.5,
  curve = 0,
  curvePivot = 0.5,
  label_offset = 0
)

Arguments

x1, y1

Start point.

x2, y2

End point.

position

Position along edge (0-1).

curve

Curvature amount.

curvePivot

Curve pivot position.

label_offset

Additional perpendicular offset for the label (in user coords). Positive values offset in the same direction as the curve bulge. Default 0.03 provides good separation from the edge line.

Value

List with x, y coordinates.


Get Edge Rendering Order

Description

Returns indices for rendering edges from weakest to strongest.

Usage

get_edge_order(edges)

Arguments

edges

Edge data frame.

Value

Integer vector of indices.


Get Edges from Cograph Network

Description

Extracts the edges data frame from a cograph_network object. For the new format, builds a data frame from the from/to/weight vectors.

Usage

get_edges(x)

Arguments

x

A cograph_network object.

Value

A data frame with columns: from, to, weight.

See Also

as_cograph, n_edges, get_nodes

Examples

mat <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)
net <- as_cograph(mat)
get_edges(net)

Get Labels from Cograph Network

Description

Extracts the node labels vector from a cograph_network object.

Usage

get_labels(x)

Arguments

x

A cograph_network object.

Value

A character vector of node labels.

See Also

as_cograph, get_nodes

Examples

mat <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)
net <- as_cograph(mat)
get_labels(net)

Get a Registered Layout

Description

Get a Registered Layout

Usage

get_layout(name)

Arguments

name

Character. Name of the layout.

Value

The layout function, or NULL if not found.

Examples

get_layout("circle")

Get Node Rendering Order

Description

Returns indices for rendering nodes from largest to smallest.

Usage

get_node_order(sizes)

Arguments

sizes

Vector of node sizes.

Value

Integer vector of indices.


Get Nodes from Cograph Network

Description

Extracts the nodes data frame from a cograph_network object.

Usage

get_nodes(x)

Arguments

x

A cograph_network object.

Value

A data frame with columns: id, label, name, x, y (and possibly others).

See Also

as_cograph, n_nodes, get_edges

Examples

mat <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)
net <- as_cograph(mat)
get_nodes(net)

Get Scaling Constants

Description

Returns the appropriate scaling constants based on the scaling mode.

Usage

get_scale_constants(scaling = "default")

Arguments

scaling

Character: "default" for qgraph-matched scaling, "legacy" for pre-v2.0 behavior.

Value

A list of scaling constants.


Get a Registered Shape

Description

Get a Registered Shape

Usage

get_shape(name)

Arguments

name

Character. Name of the shape.

Value

The shape drawing function, or NULL if not found.

Examples

get_shape("circle")

Get Shape Vertices

Description

Dispatch function to get vertices for any supported shape.

Usage

get_shape_vertices(shape, x, y, r, r2 = NULL, ...)

Arguments

shape

Shape name.

x

Center x coordinate.

y

Center y coordinate.

r

Radius/size.

r2

Secondary radius (for ellipse, rectangle).

...

Additional shape-specific parameters.

Value

List with x, y vectors of vertices.


Get Significance Stars from P-values

Description

Converts p-values to significance stars following conventional thresholds.

Usage

get_significance_stars(p)

Arguments

p

Numeric p-value(s).

Value

Character vector of stars.


Get Registered SVG Shape

Description

Retrieve SVG shape data by name.

Usage

get_svg_shape(name)

Arguments

name

Shape name.

Value

SVG data list or NULL if not found.


Get Template from Style Preset

Description

Converts a style preset name to its corresponding template string.

Usage

get_template_from_style(style)

Arguments

style

Style preset: "none", "estimate", "full", "range", "stars".

Value

Template string or NULL for "none".


Get a Registered Theme

Description

Get a Registered Theme

Usage

get_theme(name)

Arguments

name

Character. Name of the theme.

Value

The theme object, or NULL if not found.

Examples

get_theme("classic")

Get X-axis Scale Factor (inches per user unit)

Description

Get X-axis Scale Factor (inches per user unit)

Usage

get_x_scale()

Value

Scale factor.


Get Y-axis Scale Factor (inches per user unit)

Description

Get Y-axis Scale Factor (inches per user unit)

Usage

get_y_scale()

Value

Scale factor.


Global Registries for cograph

Description

Internal registries for shapes, layouts, and themes.


Handle Deprecated Parameter

Description

Handles backwards compatibility for renamed parameters. If the old parameter name is used (not NULL), issues a deprecation warning and returns the old value. Otherwise returns the new parameter value.

Usage

handle_deprecated_param(
  new_val,
  old_val,
  new_name,
  old_name,
  new_val_was_set = NULL
)

Arguments

new_val

The value of the new parameter name.

old_val

The value of the old (deprecated) parameter name.

new_name

Character string of the new parameter name (for warning message).

old_name

Character string of the old parameter name (for warning message).

new_val_was_set

Logical. TRUE if the user explicitly set new_val (FALSE means it's just the default). When NULL, the function checks if new_val is NULL to determine this.

Details

For parameters with defaults, use new_val_was_set to indicate whether the user explicitly provided the new value. If FALSE (user didn't set it) and old_val is provided, the old value takes precedence.

Value

The effective parameter value.


Check if a package is available

Description

Internal wrapper around requireNamespace that can be mocked in tests.

Usage

has_package(pkg)

Arguments

pkg

Package name.

Value

Logical.


Generate Heart Vertices

Description

Generate Heart Vertices

Usage

heart_vertices(x, y, r, n = 100)

Arguments

x

Center x coordinate.

y

Center y coordinate.

r

Scale (size).

n

Number of vertices.

Value

List with x, y vectors of vertices.


Generate Hexagon Vertices

Description

Generate Hexagon Vertices

Usage

hexagon_vertices(x, y, r)

Arguments

x

Center x coordinate.

y

Center y coordinate.

r

Radius.

Value

List with x, y vectors of vertices.


Convert Inches to User Coordinates (X-axis)

Description

Convert Inches to User Coordinates (X-axis)

Usage

in_to_usr_x(x)

Arguments

x

Value in inches.

Value

Value in user coordinates.


Convert Inches to User Coordinates (Y-axis)

Description

Convert Inches to User Coordinates (Y-axis)

Usage

in_to_usr_y(y)

Arguments

y

Value in inches.

Value

Value in user coordinates.


Initialize Global Registries

Description

Initialize Global Registries

Usage

init_registries()

Edge List Input Parsing

Description

Functions for parsing edge list data frames.


igraph Input Parsing

Description

Functions for parsing igraph objects.


Matrix Input Parsing

Description

Functions for parsing adjacency/weight matrices.


Input Parsing Functions

Description

Functions for parsing network input into internal format.


qgraph Input Parsing

Description

Functions for parsing qgraph objects.


Statnet Network Input Parsing

Description

Functions for parsing statnet network objects.


tna Input Parsing

Description

Functions for parsing tna objects.


Inset Polygon Vertices

Description

Creates an inner polygon by scaling vertices toward the centroid.

Usage

inset_polygon_vertices(outer, inner_ratio)

Arguments

outer

List with x, y vectors of outer polygon vertices.

inner_ratio

Ratio to scale vertices toward center (0-1).

Value

List with x, y vectors of inner polygon vertices.


Check if object is a CographNetwork

Description

Check if object is a CographNetwork

Usage

is_cograph_network(x)

Arguments

x

Object to check.

Value

Logical.


Check if object is a CographTheme

Description

Check if object is a CographTheme

Usage

is_cograph_theme(x)

Arguments

x

Object to check.

Value

Logical.


Check if Network is Directed

Description

Checks whether a cograph_network is directed.

Usage

is_directed(x)

Arguments

x

A cograph_network object.

Value

Logical: TRUE if directed, FALSE if undirected.

See Also

as_cograph

Examples

# Symmetric matrix -> undirected
mat <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)
net <- as_cograph(mat)
is_directed(net)  # FALSE

# Asymmetric matrix -> directed
mat2 <- matrix(c(0, 1, 0, 0, 0, 1, 0, 0, 0), nrow = 3)
net2 <- as_cograph(mat2)
is_directed(net2)  # TRUE

Detect if Matrix is Symmetric

Description

Detect if Matrix is Symmetric

Usage

is_symmetric_matrix(m, tol = .Machine$double.eps^0.5)

Arguments

m

A matrix.

tol

Tolerance for comparison.

Value

Logical.


Circular Layout

Description

Arrange nodes in a circle.


Group-based Layout

Description

Arrange nodes in groups, with each group in a circular arrangement.


Oval/Ellipse Layout

Description

Arrange nodes in an oval (ellipse) shape.


Layout Registry Functions

Description

Functions for registering built-in layouts.


Fruchterman-Reingold Spring Layout

Description

Force-directed layout using the Fruchterman-Reingold algorithm.


Bipartite Layout

Description

Arrange nodes in two columns by type.

Usage

layout_bipartite_fn(network, types = NULL, ...)

Arguments

network

A CographNetwork object.

types

Vector of type assignments. If NULL, alternates between two types.

...

Additional arguments (ignored).

Value

Data frame with x, y coordinates.


Circular Layout

Description

Arrange nodes evenly spaced around a circle.

Usage

layout_circle(network, order = NULL, start_angle = pi/2, clockwise = TRUE)

Arguments

network

A CographNetwork object.

order

Optional vector specifying node order (indices or labels).

start_angle

Starting angle in radians (default: pi/2 for top).

clockwise

Logical. Arrange nodes clockwise? Default TRUE.

Value

Data frame with x, y coordinates.

Examples

adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)
net <- CographNetwork$new(adj)
coords <- layout_circle(net)

Custom Layout (passthrough)

Description

Pass user-provided coordinates through to the layout.

Usage

layout_custom_fn(network, coords, ...)

Arguments

network

A CographNetwork object.

coords

Data frame or matrix with x, y columns.

...

Additional arguments (ignored).

Value

Data frame with x, y coordinates.


Gephi Fruchterman-Reingold Layout

Description

Force-directed layout that replicates Gephi's Fruchterman-Reingold algorithm. This is a strict port of the Java implementation from Gephi's source code.

Usage

layout_gephi_fr(g, area = 10000, gravity = 10, speed = 1, niter = 100)

Arguments

g

An igraph graph object.

area

Area parameter controlling node spread. Default 10000.

gravity

Gravity force pulling nodes toward center. Default 10.0.

speed

Speed/cooling parameter. Default 1.0.

niter

Number of iterations. Default 100.

Details

This layout is a direct port of Gephi's ForceAtlas algorithm variant of Fruchterman-Reingold. Key differences from igraph's layout_with_fr:

Value

A matrix with x,y coordinates for each node.


Grid Layout

Description

Arrange nodes in a grid pattern.

Usage

layout_grid_fn(network, ncol = NULL, ...)

Arguments

network

A CographNetwork object.

ncol

Number of columns. If NULL, computed as ceiling(sqrt(n)).

...

Additional arguments (ignored).

Value

Data frame with x, y coordinates.


Group-based Layout

Description

Arrange nodes based on group membership. Groups are positioned in a circular arrangement around the center, with nodes within each group also arranged in a circle.

Usage

layout_groups(
  network,
  groups,
  group_positions = NULL,
  inner_radius = 0.15,
  outer_radius = 0.35
)

Arguments

network

A CographNetwork object.

groups

Vector specifying group membership for each node. Can be numeric, character, or factor.

group_positions

Optional list or data frame with x, y coordinates for each group center.

inner_radius

Radius of nodes within each group (default: 0.15).

outer_radius

Radius for positioning group centers (default: 0.35).

Value

Data frame with x, y coordinates.

Examples

# Create a network with groups
adj <- matrix(0, 9, 9)
adj[1, 2:3] <- 1; adj[2:3, 1] <- 1  # Group 1
adj[4, 5:6] <- 1; adj[5:6, 4] <- 1  # Group 2
adj[7, 8:9] <- 1; adj[8:9, 7] <- 1  # Group 3
net <- CographNetwork$new(adj)
groups <- c(1, 1, 1, 2, 2, 2, 3, 3, 3)
coords <- layout_groups(net, groups)

Oval Layout

Description

Arrange nodes evenly spaced around an ellipse. This creates an oval-shaped network layout that is wider than it is tall (or vice versa depending on ratio).

Usage

layout_oval(
  network,
  ratio = 1.5,
  order = NULL,
  start_angle = pi/2,
  clockwise = TRUE,
  rotation = 0
)

Arguments

network

A CographNetwork object.

ratio

Aspect ratio (width/height). Values > 1 create horizontal ovals, values < 1 create vertical ovals. Default 1.5.

order

Optional vector specifying node order (indices or labels).

start_angle

Starting angle in radians (default: pi/2 for top).

clockwise

Logical. Arrange nodes clockwise? Default TRUE.

rotation

Rotation angle in radians to tilt the entire oval. Default 0.

Value

Data frame with x, y coordinates.

Examples

adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)
net <- CographNetwork$new(adj)
coords <- layout_oval(net, ratio = 1.5)

Random Layout

Description

Place nodes at random positions.

Usage

layout_random_fn(network, seed = NULL, ...)

Arguments

network

A CographNetwork object.

seed

Random seed. If NULL, no seed is set.

...

Additional arguments (ignored).

Value

Data frame with x, y coordinates.


Fruchterman-Reingold Spring Layout

Description

Compute node positions using the Fruchterman-Reingold force-directed algorithm. Nodes connected by edges are attracted to each other while all nodes repel each other.

Usage

layout_spring(
  network,
  iterations = 500,
  cooling = 0.95,
  repulsion = 1,
  attraction = 1,
  seed = NULL,
  initial = NULL
)

Arguments

network

A CographNetwork object.

iterations

Number of iterations (default: 500).

cooling

Rate of temperature decrease (default: 0.95).

repulsion

Repulsion constant (default: 1).

attraction

Attraction constant (default: 1).

seed

Random seed for reproducibility.

initial

Optional initial coordinates (matrix or data frame).

Value

Data frame with x, y coordinates.

Examples

adj <- matrix(c(0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0), nrow = 4)
net <- CographNetwork$new(adj)
coords <- layout_spring(net, seed = 42)

Star Layout

Description

Place one node at center, rest in a circle.

Usage

layout_star_fn(network, center = 1, ...)

Arguments

network

A CographNetwork object.

center

Index of the center node. Default 1.

...

Additional arguments (ignored).

Value

Data frame with x, y coordinates.


List Available Layouts

Description

List Available Layouts

Usage

list_layouts()

Value

Character vector of registered layout names.

Examples

list_layouts()

List Available Color Palettes

Description

Returns the names of all registered color palettes.

Usage

list_palettes()

Value

Character vector of palette names.

Examples

list_palettes()

List Available Shapes

Description

List Available Shapes

Usage

list_shapes()

Value

Character vector of registered shape names.

Examples

list_shapes()

List Registered SVG Shapes

Description

Get names of all registered custom SVG shapes.

Usage

list_svg_shapes()

Value

Character vector of registered shape names.

Examples

list_svg_shapes()

List Available Themes

Description

List Available Themes

Usage

list_themes()

Value

Character vector of registered theme names.

Examples

list_themes()

Map Edge Colors by Weight

Description

Map edge colors based on weight values.

Usage

map_edge_colors(
  weights,
  positive_color = "#2E7D32",
  negative_color = "#C62828",
  zero_color = "gray50"
)

Arguments

weights

Numeric weight values.

positive_color

Color for positive weights.

negative_color

Color for negative weights.

zero_color

Color for zero weights.

Value

Character vector of colors.


Map Node Colors by Group

Description

Helper function to map node colors based on group membership.

Usage

map_node_colors(groups, palette = NULL)

Arguments

groups

Vector of group assignments.

palette

Color palette (function or character vector).

Value

Character vector of colors.


Map qgraph lty codes to cograph edge style names

Description

Map qgraph lty codes to cograph edge style names

Usage

map_qgraph_lty(lty)

Arguments

lty

Numeric or character vector of R line types

Value

Character vector of cograph style names


Map qgraph shape names to cograph equivalents

Description

Map qgraph shape names to cograph equivalents

Usage

map_qgraph_shape(shapes)

Arguments

shapes

Character vector of qgraph shape names

Value

Character vector of cograph shape names


Plot Methods

Description

S3 plot methods for Cograph objects.


Print Methods

Description

S3 print methods for Cograph objects.


Get Number of Edges

Description

Returns the number of edges in a cograph_network.

Usage

n_edges(x)

Arguments

x

A cograph_network object.

Value

Integer: number of edges.

See Also

as_cograph, n_nodes

Examples

mat <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)
net <- as_cograph(mat)
n_edges(net)  # 3

Get Number of Nodes

Description

Returns the number of nodes in a cograph_network.

Usage

n_nodes(x)

Arguments

x

A cograph_network object.

Value

Integer: number of nodes.

See Also

as_cograph, n_edges, get_nodes

Examples

mat <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)
net <- as_cograph(mat)
n_nodes(net)  # 3

Get Nodes from Cograph Network (Deprecated)

Description

Extracts the nodes data frame from a cograph_network object. Deprecated: Use get_nodes instead.

Usage

nodes(x)

Arguments

x

A cograph_network object.

Value

A data frame with columns: id, label, name, x, y (and possibly others).

See Also

get_nodes, as_cograph, n_nodes

Examples

mat <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)
net <- as_cograph(mat)
nodes(net)  # Deprecated, use get_nodes(net) instead

Offset Point from Center

Description

Calculate a point offset from another point by a given distance.

Usage

offset_point(x, y, toward_x, toward_y, offset)

Arguments

x, y

Original point.

toward_x, toward_y

Point to offset toward.

offset

Distance to offset.

Value

List with x, y coordinates.


Output and Saving

Description

Functions for saving network visualizations to files.


Blues Palette

Description

Generate a blue sequential palette.

Usage

palette_blues(n, alpha = 1)

Arguments

n

Number of colors to generate.

alpha

Transparency (0-1).

Value

Character vector of colors.

Examples

palette_blues(5)

Colorblind-friendly Palette

Description

Generate a colorblind-friendly palette using Wong's colors.

Usage

palette_colorblind(n, alpha = 1)

Arguments

n

Number of colors to generate.

alpha

Transparency (0-1).

Value

Character vector of colors.

Examples

palette_colorblind(5)

Diverging Palette

Description

Generate a diverging color palette (blue-white-red).

Usage

palette_diverging(n, alpha = 1, midpoint = "white")

Arguments

n

Number of colors to generate.

alpha

Transparency (0-1).

midpoint

Color for midpoint.

Value

Character vector of colors.

Examples

palette_diverging(5)

Pastel Palette

Description

Generate a soft pastel color palette.

Usage

palette_pastel(n, alpha = 1)

Arguments

n

Number of colors to generate.

alpha

Transparency (0-1).

Value

Character vector of colors.

Examples

palette_pastel(5)

Rainbow Palette

Description

Generate a rainbow color palette.

Usage

palette_rainbow(n, alpha = 1)

Arguments

n

Number of colors to generate.

alpha

Transparency (0-1).

Value

Character vector of colors.

Examples

palette_rainbow(5)

Reds Palette

Description

Generate a red sequential palette.

Usage

palette_reds(n, alpha = 1)

Arguments

n

Number of colors to generate.

alpha

Transparency (0-1).

Value

Character vector of colors.

Examples

palette_reds(5)

Viridis Palette

Description

Generate colors from the viridis palette.

Usage

palette_viridis(n, alpha = 1, option = "viridis")

Arguments

n

Number of colors to generate.

alpha

Transparency (0-1).

option

Viridis option: "viridis", "magma", "plasma", "inferno", "cividis".

Value

Character vector of colors.

Examples

palette_viridis(5)

Color Palettes

Description

Built-in color palettes for network visualization.


Parse Network Input

Description

Automatically detects input type and converts to internal format.

Usage

parse_input(input, directed = NULL)

Arguments

input

Network input: matrix, data.frame (edge list), or igraph object.

directed

Logical. Force directed interpretation. NULL for auto-detect.

Value

List with nodes, edges, directed, and weights components.


Parse SVG Content

Description

Parse SVG from string or file.

Usage

parse_svg(svg_data)

Arguments

svg_data

SVG data list from registry.

Value

Parsed SVG object (grImport2 Picture or NULL).


Generate Pentagon Vertices

Description

Generate Pentagon Vertices

Usage

pentagon_vertices(x, y, r)

Arguments

x

Center x coordinate.

y

Center y coordinate.

r

Radius.

Value

List with x, y vectors of vertices.


Calculate Perpendicular Midpoint for Curved Edges

Description

Computes a control point perpendicular to the line between two nodes, used for xspline() curve generation.

Usage

perp_mid(x0, y0, x1, y1, cex, q = 0.5)

Arguments

x0

Start x coordinate.

y0

Start y coordinate.

x1

End x coordinate.

y1

End y coordinate.

cex

Curvature amount (positive = left, negative = right).

q

Position along edge (0 = start, 0.5 = middle, 1 = end).

Value

List with x, y coordinates of control point.


Plot cograph_network Object

Description

Plot cograph_network Object

Usage

## S3 method for class 'cograph_network'
plot(x, ...)

Arguments

x

A cograph_network object.

...

Additional arguments passed to sn_render.

Value

Invisible x.

Examples

adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)
net <- cograph(adj)
plot(net)

Plot Heterogeneous TNA Network (Multi-Group Layout)

Description

Plots a TNA model with nodes arranged in multiple groups using geometric layouts:

Supports triangle (3), rectangle (4), pentagon (5), hexagon (6), and beyond.

Usage

plot_htna(
  x,
  node_list,
  layout = "auto",
  use_list_order = TRUE,
  jitter = TRUE,
  jitter_amount = 0.8,
  jitter_side = "first",
  orientation = "vertical",
  group1_pos = -1.2,
  group2_pos = 1.2,
  curvature = 0.4,
  group1_color = "#ffd89d",
  group2_color = "#a68ba5",
  group1_shape = "circle",
  group2_shape = "square",
  group_colors = NULL,
  group_shapes = NULL,
  angle_spacing = 0.15,
  edge_colors = NULL,
  legend = TRUE,
  legend_position = "topright",
  extend_lines = FALSE,
  scale = 1,
  ...
)

Arguments

x

A tna object or weight matrix.

node_list

List of 2+ character vectors defining node groups.

layout

Layout type: "auto" (default), "bipartite", "polygon", or "circular". When "auto", uses bipartite for 2 groups and polygon for 3+ groups. "circular" places groups along arcs of a circle. Legacy values "triangle" and "rectangle" are supported as aliases for "polygon".

use_list_order

Logical. Use node_list order (TRUE) or weight-based order (FALSE). Only applies to bipartite layout.

jitter

Controls horizontal spread of nodes. Options:

  • TRUE (default): Auto-compute jitter based on edge connectivity

  • FALSE or 0: No jitter (nodes aligned in columns)

  • Numeric (0-1): Amount of jitter (0.3 = spread nodes 30\

  • Named list: Manual per-node offsets by label (e.g., list(Wrong = -0.2))

  • Numeric vector of length n: Direct x-offsets for each node

Only applies to bipartite layout.

jitter_amount

Base jitter amount when jitter=TRUE. Default 0.5. Higher values spread nodes more toward the center. Only applies to bipartite layout.

jitter_side

Which side(s) to apply jitter: "first", "second", "both", or "none". Default "first" (only first group nodes are jittered toward center). Only applies to bipartite layout.

orientation

Layout orientation for bipartite: "vertical" (two columns, default) or "horizontal" (two rows). Ignored for triangle/rectangle layouts.

group1_pos

Position for first group in bipartite layout. Default -1.2.

group2_pos

Position for second group in bipartite layout. Default 1.2.

curvature

Edge curvature amount. Default 0.4 for visible curves.

group1_color

Color for first group nodes. Default "#ffd89d".

group2_color

Color for second group nodes. Default "#a68ba5".

group1_shape

Shape for first group nodes. Default "circle".

group2_shape

Shape for second group nodes. Default "square".

group_colors

Vector of colors for each group. Overrides group1_color/group2_color. Required for 3+ groups if not using defaults.

group_shapes

Vector of shapes for each group. Overrides group1_shape/group2_shape. Required for 3+ groups if not using defaults.

angle_spacing

Controls empty space at corners (0-1). Default 0.15. Higher values create larger empty angles at vertices. Only applies to triangle/rectangle layouts.

edge_colors

Vector of colors for edges by source group. If NULL (default), uses darker versions of group_colors. Set to FALSE to use default edge color.

legend

Logical. Whether to show a legend. Default TRUE for polygon layouts.

legend_position

Position for legend: "topright", "topleft", "bottomright", "bottomleft", "right", "left", "top", "bottom". Default "topright".

extend_lines

Logical or numeric. Draw extension lines from nodes. Only applies to bipartite layout.

  • FALSE (default): No extension lines

  • TRUE: Draw lines extending toward the other group (default length 0.1)

  • Numeric: Length of extension lines

scale

Scaling factor for high resolution plotting.

...

Additional parameters passed to tplot().

Value

Invisibly returns the result from tplot().

Examples

# --- 2-group bipartite example ---
nodes_2 <- c("Wrong", "Retry", "Right", "Attempt", "Instruction", "Skip",
              "Order", "Correct", "Hint", "Quit", "Clarify", "Question", "Praise")
set.seed(1)
m2 <- matrix(runif(length(nodes_2)^2, 0, 0.3), length(nodes_2), length(nodes_2))
diag(m2) <- 0
dimnames(m2) <- list(nodes_2, nodes_2)

node_types <- list(
  Student = c("Wrong", "Retry", "Right", "Attempt", "Instruction", "Skip"),
  AI = c("Order", "Correct", "Hint", "Quit", "Clarify", "Question", "Praise")
)
plot_htna(m2, node_types)
plot_htna(m2, node_types, jitter_amount = 0.5)

# --- Triangle layout (3 groups) ---
nodes_3 <- c("Explain", "Question", "Feedback",
              "Answer", "Ask", "Attempt",
              "Hint", "Score", "Progress")
m3 <- matrix(runif(81, 0, 0.3), 9, 9)
diag(m3) <- 0
dimnames(m3) <- list(nodes_3, nodes_3)

node_types_3 <- list(
  Teacher = c("Explain", "Question", "Feedback"),
  Student = c("Answer", "Ask", "Attempt"),
  System  = c("Hint", "Score", "Progress")
)
plot_htna(m3, node_types_3)
plot_htna(m3, node_types_3, layout = "triangle")

# --- Rectangle layout (4 groups) ---
nodes_4 <- c("Click", "Type", "Scroll",
              "Validate", "Transform",
              "Display", "Alert",
              "Save", "Load", "Cache")
m4 <- matrix(runif(100, 0, 0.3), 10, 10)
diag(m4) <- 0
dimnames(m4) <- list(nodes_4, nodes_4)

node_types_4 <- list(
  Input   = c("Click", "Type", "Scroll"),
  Process = c("Validate", "Transform"),
  Output  = c("Display", "Alert"),
  Storage = c("Save", "Load", "Cache")
)
plot_htna(m4, node_types_4)

Multilevel Network Visualization

Description

Visualizes multilevel/multiplex networks where multiple layers are stacked in a 3D perspective view. Each layer contains nodes connected by solid edges (within-layer), while dashed lines connect nodes between adjacent layers (inter-layer edges). Each layer is enclosed in a parallelogram shell giving a pseudo-3D appearance.

Usage

plot_mlna(
  model,
  layer_list,
  layout = "horizontal",
  layer_spacing = 2.2,
  layer_width = 4.5,
  layer_depth = 2.2,
  skew_angle = 25,
  node_spacing = 0.7,
  colors = NULL,
  shapes = NULL,
  edge_colors = NULL,
  within_edges = TRUE,
  between_edges = TRUE,
  between_style = 2,
  show_border = TRUE,
  legend = TRUE,
  legend_position = "topright",
  curvature = 0.15,
  node_size = 3,
  minimum = 0,
  scale = 1,
  ...
)

mlna(
  model,
  layer_list,
  layout = "horizontal",
  layer_spacing = 2.2,
  layer_width = 4.5,
  layer_depth = 2.2,
  skew_angle = 25,
  node_spacing = 0.7,
  colors = NULL,
  shapes = NULL,
  edge_colors = NULL,
  within_edges = TRUE,
  between_edges = TRUE,
  between_style = 2,
  show_border = TRUE,
  legend = TRUE,
  legend_position = "topright",
  curvature = 0.15,
  node_size = 3,
  minimum = 0,
  scale = 1,
  ...
)

Arguments

model

A tna object or weight matrix.

layer_list

List of character vectors defining layers. Each element contains node names belonging to that layer. Layers are displayed from top to bottom in list order.

layout

Node layout within layers: "horizontal" (default) spreads nodes horizontally, "circle" arranges nodes in an ellipse, "spring" uses force-directed placement based on within-layer connections.

layer_spacing

Vertical distance between layer centers. Default 2.2.

layer_width

Horizontal width of each layer shell. Default 4.5.

layer_depth

Depth of each layer (for 3D effect). Default 2.2.

skew_angle

Angle of perspective skew in degrees. Default 25.

node_spacing

Node placement ratio within layer (0-1). Default 0.7. Higher values spread nodes closer to the layer edges.

colors

Vector of colors for each layer. Default auto-generated.

shapes

Vector of shapes for each layer. Default cycles through "circle", "square", "diamond", "triangle".

edge_colors

Vector of edge colors by source layer. If NULL (default), uses darker versions of layer colors.

within_edges

Logical. Show edges within layers (solid lines). Default TRUE.

between_edges

Logical. Show edges between adjacent layers (dashed lines). Default TRUE.

between_style

Line style for between-layer edges. Default 2 (dashed). Use 1 for solid, 3 for dotted.

show_border

Logical. Draw parallelogram shells around layers. Default TRUE.

legend

Logical. Whether to show legend. Default TRUE.

legend_position

Position for legend. Default "topright".

curvature

Edge curvature for within-layer edges. Default 0.15.

node_size

Size of nodes. Default 2.5.

minimum

Minimum edge weight threshold. Edges below this are hidden. Default 0.

scale

Scaling factor for high resolution plotting.

...

Additional parameters (currently unused).

Details

Multilevel network example

Value

Invisibly returns NULL.

Examples

# Create multilevel network
set.seed(42)
nodes <- paste0("N", 1:15)
m <- matrix(runif(225, 0, 0.3), 15, 15)
diag(m) <- 0
colnames(m) <- rownames(m) <- nodes

# Define 3 layers
layers <- list(
  Macro = paste0("N", 1:5),
  Meso = paste0("N", 6:10),
  Micro = paste0("N", 11:15)
)

# Basic usage
plot_mlna(m, layers)

# Customized
plot_mlna(m, layers,
     layer_spacing = 2.5,
     layer_width = 5,
     between_style = 2,  # dashed
     minimum = 0.1)

# Circle layout within layers
plot_mlna(m, layers, layout = "circle")

Multi-Cluster TNA Network Plot

Description

Visualizes multiple network clusters with summary edges between clusters and individual edges within clusters. Each cluster is displayed as a shape (circle, square, diamond, triangle) containing its nodes.

Usage

plot_mtna(
  x,
  cluster_list,
  layout = "circle",
  spacing = 3,
  shape_size = 1.2,
  node_spacing = 0.5,
  colors = NULL,
  shapes = NULL,
  edge_colors = NULL,
  bundle_edges = TRUE,
  bundle_strength = 0.8,
  summary_edges = TRUE,
  within_edges = TRUE,
  show_border = TRUE,
  legend = TRUE,
  legend_position = "topright",
  curvature = 0.3,
  node_size = 2,
  scale = 1,
  ...
)

mtna(
  x,
  cluster_list,
  layout = "circle",
  spacing = 3,
  shape_size = 1.2,
  node_spacing = 0.5,
  colors = NULL,
  shapes = NULL,
  edge_colors = NULL,
  bundle_edges = TRUE,
  bundle_strength = 0.8,
  summary_edges = TRUE,
  within_edges = TRUE,
  show_border = TRUE,
  legend = TRUE,
  legend_position = "topright",
  curvature = 0.3,
  node_size = 2,
  scale = 1,
  ...
)

Arguments

x

A tna object or weight matrix.

cluster_list

List of character vectors defining clusters. Each cluster becomes a separate shape in the layout.

layout

How to arrange the clusters: "circle" (default), "grid", "horizontal", "vertical".

spacing

Distance between cluster centers. Default 3.

shape_size

Size of each cluster shape (shell radius). Default 1.2.

node_spacing

Radius for node placement within shapes (0-1 relative to shape_size). Default 0.5.

colors

Vector of colors for each cluster. Default auto-generated.

shapes

Vector of shapes for each cluster: "circle", "square", "diamond", "triangle". Default cycles through these.

edge_colors

Vector of edge colors by source cluster. Default auto-generated.

bundle_edges

Logical. Bundle inter-cluster edges through channels. Default TRUE.

bundle_strength

How tightly to bundle edges (0-1). Default 0.8.

summary_edges

Logical. Show aggregated summary edges between clusters instead of individual node edges. Default TRUE.

within_edges

Logical. When summary_edges is TRUE, also show individual edges within each cluster. Default TRUE.

show_border

Logical. Draw a border around each cluster. Default TRUE.

legend

Logical. Whether to show legend. Default TRUE.

legend_position

Position for legend. Default "topright".

curvature

Edge curvature. Default 0.3.

node_size

Size of nodes inside shapes. Default 2.

scale

Scaling factor for high resolution plotting.

...

Additional parameters passed to plot_tna().

Value

Invisibly returns NULL for summary mode, or the plot_tna result.

Examples

# Create network with 4 clusters
nodes <- paste0("N", 1:20)
m <- matrix(runif(400, 0, 0.3), 20, 20)
diag(m) <- 0
colnames(m) <- rownames(m) <- nodes

clusters <- list(
  North = paste0("N", 1:5),
  East = paste0("N", 6:10),
  South = paste0("N", 11:15),
  West = paste0("N", 16:20)
)

# Summary edges between clusters + individual edges within
plot_mtna(m, clusters, summary_edges = TRUE)

# Control spacing and sizes
plot_mtna(m, clusters, spacing = 4, shape_size = 1.5, node_spacing = 0.6)

TNA-Style Network Plot (qgraph Compatible)

Description

A drop-in replacement for qgraph::qgraph() that uses cograph's splot engine. Accepts qgraph parameter names for seamless migration from qgraph to cograph.

Usage

plot_tna(
  x,
  color = NULL,
  labels = NULL,
  layout = "oval",
  theme = "colorblind",
  mar = c(0.1, 0.1, 0.1, 0.1),
  cut = NULL,
  edge.labels = TRUE,
  edge.label.position = 0.7,
  edge.label.cex = 0.6,
  edge.color = "#003355",
  vsize = 7,
  pie = NULL,
  pieColor = NULL,
  lty = NULL,
  directed = NULL,
  minimum = NULL,
  posCol = NULL,
  negCol = NULL,
  arrowAngle = NULL,
  title = NULL,
  ...
)

tplot(
  x,
  color = NULL,
  labels = NULL,
  layout = "oval",
  theme = "colorblind",
  mar = c(0.1, 0.1, 0.1, 0.1),
  cut = NULL,
  edge.labels = TRUE,
  edge.label.position = 0.7,
  edge.label.cex = 0.6,
  edge.color = "#003355",
  vsize = 7,
  pie = NULL,
  pieColor = NULL,
  lty = NULL,
  directed = NULL,
  minimum = NULL,
  posCol = NULL,
  negCol = NULL,
  arrowAngle = NULL,
  title = NULL,
  ...
)

Arguments

x

A weight matrix (adjacency matrix) or tna object

color

Node fill colors

labels

Node labels

layout

Layout: "circle", "spring", "oval", or a coordinate matrix

theme

Plot theme ("colorblind", "gray", etc.)

mar

Plot margins (numeric vector of length 4)

cut

Edge emphasis threshold

edge.labels

Show edge weight labels

edge.label.position

Position of edge labels along edge (0-1)

edge.label.cex

Edge label size multiplier

edge.color

Edge colors

vsize

Node size

pie

Pie/donut fill values (e.g., initial probabilities)

pieColor

Pie/donut segment colors

lty

Line type for edges (1=solid, 2=dashed, 3=dotted)

directed

Logical, is the graph directed?

minimum

Minimum edge weight to display

posCol

Color for positive edges

negCol

Color for negative edges

arrowAngle

Arrow head angle in radians. Default pi/6 (30 degrees).

title

Plot title

...

Additional arguments passed to splot()

Value

Invisibly returns the cograph_network object from splot().

Examples

# Simple usage
m <- matrix(runif(25), 5, 5)
plot_tna(m)

# With qgraph-style parameters
plot_tna(m, vsize = 15, edge.label.cex = 2, layout = "circle")

# With custom colors
plot_tna(m, color = rainbow(5), vsize = 10)


Calculate Angle Between Two Points

Description

Calculate Angle Between Two Points

Usage

point_angle(x1, y1, x2, y2)

Arguments

x1, y1

Start point coordinates.

x2, y2

End point coordinates.

Value

Angle in radians.


Calculate Distance Between Two Points

Description

Calculate Distance Between Two Points

Usage

point_distance(x1, y1, x2, y2)

Arguments

x1, y1

First point coordinates.

x2, y2

Second point coordinates.

Value

Euclidean distance.


Calculate Point on Circle

Description

Calculate Point on Circle

Usage

point_on_circle(cx, cy, r, angle)

Arguments

cx, cy

Center coordinates.

r

Radius.

angle

Angle in radians.

Value

List with x, y coordinates.


Print cograph_network Object

Description

Print cograph_network Object

Usage

## S3 method for class 'cograph_network'
print(x, ...)

Arguments

x

A cograph_network object.

...

Ignored.

Value

Invisible x.


qgraph-style Arrow Size Calculation

Description

Calculates arrow size based on edge width, matching qgraph behavior.

Usage

qgraph_arrow_size(edge_width, base_asize = 1)

Arguments

edge_width

Edge line width.

base_asize

Base arrow size multiplier.

Value

Arrow size in user coordinates.


qgraph Cent2Edge (EXACT - critical formula)

Description

Calculates the point on node boundary where an edge should connect. This is qgraph's exact formula for positioning arrows and edge endpoints.

Usage

qgraph_cent2edge(x, y, cex, offset = 0, angle, plot_info = NULL)

Arguments

x

Node center x coordinate.

y

Node center y coordinate.

cex

Node size (vsize value, not yet scaled).

offset

Additional offset distance.

angle

Angle from node center to target point (radians).

plot_info

Plot dimension info from qgraph_plot_info(). NULL to auto-compute.

Value

List with x, y coordinates on node boundary.


qgraph Point on Node Boundary

Description

Simplified boundary calculation for splot that approximates qgraph behavior while working with cograph's coordinate system.

Usage

qgraph_cent_to_edge_simple(x, y, angle, node_size, shape = "circle")

Arguments

x

Node center x coordinate.

y

Node center y coordinate.

angle

Angle to target (radians).

node_size

Node radius in user coordinates.

shape

Node shape.

Value

List with x, y coordinates on boundary.


qgraph Default Edge Size

Description

Calculates the default maximum edge width using qgraph's exact formula. Formula: 15 * exp(-n/90) + 1 (halved for directed networks, minimum 1)

Usage

qgraph_default_esize(n_nodes, weighted = TRUE, directed = FALSE)

Arguments

n_nodes

Number of nodes in the network.

weighted

Logical: is the network weighted?

directed

Logical: is the network directed?

Value

Default esize value.


qgraph Default Node Size

Description

Calculates the default node size using qgraph's exact formula. Formula: 8 * exp(-n/80) + 1

Usage

qgraph_default_vsize(n_nodes)

Arguments

n_nodes

Number of nodes in the network.

Value

Default vsize value (before scale factor conversion).


qgraph Curve Normalization Factor

Description

Calculates the normalization factor for edge curvature to maintain consistent visual appearance across different plot sizes. Formula: sqrt(sum(pin^2)) / sqrt(7^2 + 7^2)

Usage

qgraph_norm_curve()

Value

Numeric normalization factor.


Get Plot Dimension Info

Description

Retrieves current plot device information needed for qgraph-style calculations.

Usage

qgraph_plot_info()

Value

List with usr, pin, mai, csi, and dev_name components.


qgraph Edge Width Scaling (EXACT)

Description

Scales edge weights to widths using qgraph's exact formula. Output range is 1 to esize for continuous scaling (cut = 0).

Usage

qgraph_scale_edge_widths(
  weights,
  minimum = 0,
  maximum = NULL,
  cut = 0,
  esize = NULL
)

Arguments

weights

Numeric vector of edge weights.

minimum

Minimum weight threshold.

maximum

Maximum weight for normalization.

cut

Two-tier cutoff threshold. 0 = continuous scaling.

esize

Maximum edge width.

Value

Numeric vector of scaled edge widths.


qgraph Node Size to User Coordinates

Description

Converts qgraph vsize to user coordinate radius using qgraph's exact logic.

Usage

qgraph_vsize_to_user(vsize, plot_info = NULL)

Arguments

vsize

Node size value (as used in qgraph).

plot_info

Plot dimension info. NULL to auto-compute.

Value

Node radius in user coordinates.


Generate Rectangle Vertices

Description

Generate Rectangle Vertices

Usage

rectangle_vertices(x, y, w, h)

Arguments

x

Center x coordinate.

y

Center y coordinate.

w

Half-width.

h

Half-height.

Value

List with x, y vectors of vertices.


Recycle Value to Length

Description

Recycle Value to Length

Usage

recycle_to_length(x, n)

Arguments

x

Value to recycle.

n

Target length.

Value

Recycled vector.


Register Built-in Layouts

Description

Register all built-in layout algorithms.

Usage

register_builtin_layouts()

Register Built-in Palettes

Description

Register Built-in Palettes

Usage

register_builtin_palettes()

Register Built-in Shapes

Description

Register all built-in node shapes.

Usage

register_builtin_shapes()

Register Built-in Themes

Description

Register all built-in themes.

Usage

register_builtin_themes()

Register a Custom Layout

Description

Register a new layout algorithm that can be used for network visualization.

Usage

register_layout(name, layout_fn)

Arguments

name

Character. Name of the layout.

layout_fn

Function. A function that computes node positions. Should accept a CographNetwork object and return a matrix with x, y columns.

Value

Invisible NULL.

Examples

# Register a simple random layout
register_layout("random", function(network, ...) {
  n <- network$n_nodes
  cbind(x = runif(n), y = runif(n))
})

Register a Custom Shape

Description

Register a new shape that can be used for node rendering.

Usage

register_shape(name, draw_fn)

Arguments

name

Character. Name of the shape.

draw_fn

Function. A function that draws the shape. Should accept parameters: x, y, size, fill, border_color, border_width, ...

Value

Invisible NULL.

Examples

# Register a custom hexagon shape
register_shape("hexagon", function(x, y, size, fill, border_color, border_width, ...) {
  angles <- seq(0, 2 * pi, length.out = 7)
  grid::polygonGrob(
    x = x + size * cos(angles),
    y = y + size * sin(angles),
    gp = grid::gpar(fill = fill, col = border_color, lwd = border_width)
  )
})

Register Custom SVG Shape

Description

Register an SVG file or string as a custom node shape.

Usage

register_svg_shape(name, svg_source)

Arguments

name

Character: unique name for this shape (used in node_shape parameter).

svg_source

Character: path to SVG file OR inline SVG string.

Value

Invisible NULL. The shape is registered for use with sn_nodes().

Examples

# Register a custom SVG shape from an inline SVG string
register_svg_shape("simple_star",
  '<svg viewBox="0 0 100 100">
    <polygon points="50,5 20,99 95,39 5,39 80,99" fill="currentColor"/>
  </svg>')

# Create a small adjacency matrix
adj <- matrix(c(0, 1, 1, 0, 0, 1, 1, 0, 0), nrow = 3,
              dimnames = list(c("A", "B", "C"), c("A", "B", "C")))

# Use in network (requires grImport2 for SVG rendering; falls back to circle)
cograph(adj) |> sn_nodes(shape = "simple_star")

Register a Custom Theme

Description

Register a new theme for network visualization.

Usage

register_theme(name, theme)

Arguments

name

Character. Name of the theme.

theme

A CographTheme object or a list of theme parameters.

Value

Invisible NULL.

Examples

# Register a custom theme
register_theme("custom", list(
  background = "white",
  node_fill = "steelblue",
  node_border = "navy",
  edge_color = "gray50"
))

Generate Regular Polygon Vertices

Description

Generate Regular Polygon Vertices

Usage

regular_polygon_vertices(x, y, r, n, rotation = pi/2)

Arguments

x

Center x coordinate.

y

Center y coordinate.

r

Radius.

n

Number of sides.

rotation

Starting angle in radians (default: first vertex at top).

Value

List with x, y vectors of vertices.


Edge Rendering

Description

Functions for rendering edges using grid graphics.


ggplot2 Conversion

Description

Convert Cograph network to ggplot2 object.


Grid Rendering

Description

Main grid-based rendering functions.


Node Rendering

Description

Functions for rendering nodes using grid graphics.


Render Edge Labels

Description

Create grid grobs for edge labels with background, borders, and styling.

Usage

render_edge_labels_grid(network)

Arguments

network

A CographNetwork object.

Value

A grid gList of label grobs.


Render All Edges

Description

Create grid grobs for all edges in the network.

Usage

render_edges_grid(network)

Arguments

network

A CographNetwork object.

Value

A grid gList of edge grobs.


Render Edges for splot

Description

Render Edges for splot

Usage

render_edges_splot(
  edges,
  layout,
  node_sizes,
  shapes,
  edge_color,
  edge_width,
  edge_style,
  curvature,
  curve_shape,
  curve_pivot,
  show_arrows,
  arrow_size,
  arrow_angle = pi/6,
  bidirectional,
  loop_rotation,
  edge_labels,
  edge_label_size,
  edge_label_color,
  edge_label_bg,
  edge_label_position,
  edge_label_offset = 0,
  edge_label_fontface,
  edge_label_shadow = FALSE,
  edge_label_shadow_color = "gray40",
  edge_label_shadow_offset = 0.5,
  edge_label_shadow_alpha = 0.5,
  edge_ci = NULL,
  edge_ci_scale = 2,
  edge_ci_alpha = 0.15,
  edge_ci_color = NULL,
  edge_ci_style = 2,
  edge_ci_arrows = FALSE,
  is_reciprocal = NULL,
  edge_start_style = "solid",
  edge_start_length = 0.15,
  edge_start_dot_density = "12"
)

Render Legend

Description

Create grid grobs for the network legend.

Usage

render_legend_grid(network, position = "topright")

Arguments

network

A CographNetwork object.

position

Legend position: "topright", "topleft", "bottomright", "bottomleft".

Value

A grid gList of legend grobs.


Render Legend for splot

Description

Renders a comprehensive legend showing node groups, edge weight colors, and optionally node sizes.

Usage

render_legend_splot(
  groups,
  node_names,
  nodes,
  node_colors,
  position = "topright",
  cex = 0.8,
  show_edge_colors = FALSE,
  positive_color = "#2E7D32",
  negative_color = "#C62828",
  has_pos_edges = FALSE,
  has_neg_edges = FALSE,
  show_node_sizes = FALSE,
  node_size = NULL
)

Arguments

groups

Group assignments for nodes.

node_names

Names for legend entries.

nodes

Node data frame.

node_colors

Vector of node colors.

position

Legend position.

cex

Text size.

show_edge_colors

Logical: show positive/negative edge color legend?

positive_color

Positive edge color.

negative_color

Negative edge color.

has_pos_edges

Logical: are there positive weighted edges?

has_neg_edges

Logical: are there negative weighted edges?

show_node_sizes

Logical: show node size legend?

node_size

Vector of node sizes.


Render Node Labels

Description

Create grid grobs for node labels.

Usage

render_node_labels_grid(network)

Arguments

network

A CographNetwork object.

Value

A grid gList of label grobs.


Render All Nodes

Description

Renders all nodes in the network.

Usage

render_nodes_base(
  layout,
  vsize,
  vsize2 = NULL,
  shape = "circle",
  color = "#4A90D9",
  border.color = "#2C5AA0",
  border.width = 1,
  pie = NULL,
  pieColor = NULL,
  donut = NULL,
  donutColor = NULL,
  labels = NULL,
  label.cex = 1,
  label.color = "black"
)

Arguments

layout

Matrix with x, y columns.

vsize

Vector of node sizes.

vsize2

Vector of secondary sizes (for ellipse).

shape

Vector of shape names.

color

Vector of fill colors.

border.color

Vector of border colors.

border.width

Vector of border widths.

pie

List of pie value vectors (one per node) or NULL.

pieColor

List of pie color vectors or NULL.

donut

List of donut values or NULL.

donutColor

List of donut color vectors or NULL.

labels

Vector of labels or NULL.

label.cex

Vector of label sizes.

label.color

Vector of label colors.


Render All Nodes

Description

Create grid grobs for all nodes in the network.

Usage

render_nodes_grid(network)

Arguments

network

A CographNetwork object.

Value

A grid gList of node grobs.


Render Nodes for splot

Description

Render Nodes for splot

Usage

render_nodes_splot(
  layout,
  node_size,
  node_size2,
  node_shape,
  node_fill,
  node_border_color,
  node_border_width,
  pie_values,
  pie_colors,
  pie_border_width,
  donut_values,
  donut_colors,
  donut_border_color,
  donut_border_width,
  donut_outer_border_color = NULL,
  donut_line_type = "solid",
  donut_inner_ratio,
  donut_bg_color,
  donut_shape,
  donut_show_value,
  donut_value_size,
  donut_value_color,
  donut_value_fontface = "bold",
  donut_value_fontfamily = "sans",
  donut_value_digits = 2,
  donut_value_prefix = "",
  donut_value_suffix = "",
  donut2_values,
  donut2_colors,
  donut2_inner_ratio,
  labels,
  label_size,
  label_color,
  label_position,
  label_fontface = "plain",
  label_fontfamily = "sans",
  label_hjust = 0.5,
  label_vjust = 0.5,
  label_angle = 0,
  use_pch = FALSE
)

Arguments

donut_values

List of values for donut chart. Each element is a single numeric (0-1) representing fill proportion for that node.


Rescale Layout to -1 to 1 Range

Description

Rescale Layout to -1 to 1 Range

Usage

rescale_layout(layout, mar = 0.1)

Arguments

layout

Matrix or data frame with x, y columns.

mar

Margin to leave (as proportion of range).

Value

Rescaled layout.


Resolve Aesthetic Value

Description

Resolve an aesthetic value that could be a constant, vector, or column name.

Usage

resolve_aesthetic(value, data = NULL, n = NULL, default = NULL)

Arguments

value

Value to resolve.

data

Data frame to look up column names.

n

Expected length.

default

Default value if NULL.

Value

Resolved vector of values.


Resolve Curvature Parameter

Description

Determines edge curvatures, handling reciprocal edges.

Usage

resolve_curvatures(curve, edges, curveScale = TRUE, default_curve = 0.2)

Arguments

curve

User-specified curvature(s).

edges

Edge data frame.

curveScale

Logical: scale curvature for reciprocal edges?

default_curve

Default curvature for reciprocal edges.

Value

Vector of curvatures.


Resolve Edge Colors

Description

Determines edge colors based on weights, explicit colors, or defaults.

Usage

resolve_edge_colors(
  edges,
  edge.color = NULL,
  posCol = "#2E7D32",
  negCol = "#C62828",
  default_col = "gray50"
)

Arguments

edges

Edge data frame with from, to, weight columns.

edge.color

User-specified edge color(s) or NULL.

posCol

Color for positive weights.

negCol

Color for negative weights.

default_col

Default color when no weight.

Value

Vector of colors for each edge.


Resolve Edge Labels

Description

Determines edge labels from various inputs.

Usage

resolve_edge_labels(edge.labels, edges, m)

Arguments

edge.labels

User-specified labels: TRUE, FALSE, character vector, or NULL.

edges

Edge data frame.

m

Number of edges.

Value

Character vector of labels (or NULL for no labels).


Resolve Edge Widths

Description

Determines edge widths based on weights or explicit values. Supports multiple scaling modes, two-tier cutoff, and output range specification.

Usage

resolve_edge_widths(
  edges,
  edge.width = NULL,
  esize = NULL,
  n_nodes = NULL,
  directed = FALSE,
  maximum = NULL,
  minimum = 0,
  cut = NULL,
  edge_width_range = NULL,
  edge_scale_mode = NULL,
  scaling = "default",
  base_width = NULL,
  scale_factor = NULL
)

Arguments

edges

Edge data frame.

edge.width

User-specified width(s) or NULL.

esize

Base edge size. NULL uses adaptive sizing based on n_nodes.

n_nodes

Number of nodes (for adaptive esize calculation).

directed

Whether network is directed.

maximum

Maximum weight for scaling (NULL for auto).

minimum

Minimum weight threshold.

cut

Two-tier cutoff. NULL = auto (75th pct), 0 = disabled.

edge_width_range

Output width range c(min, max).

edge_scale_mode

Scaling mode: "linear", "log", "sqrt", "rank".

scaling

Scaling mode for constants: "default" or "legacy".

base_width

Legacy: Base width value.

scale_factor

Legacy: Width scaling factor.

Value

Vector of widths for each edge.


Resolve Label Sizes

Description

Determines label sizes, either independent (new default) or coupled to node size (legacy).

Usage

resolve_label_sizes(label_size, node_size_usr, n, scaling = "default")

Arguments

label_size

User-specified label size(s) or NULL.

node_size_usr

Node sizes in user coordinates (for legacy coupled mode).

n

Number of nodes.

scaling

Scaling mode: "default" or "legacy".

Value

Vector of label sizes (cex values).


Resolve Labels

Description

Determines node labels from various inputs.

Usage

resolve_labels(labels, nodes, n)

Arguments

labels

User-specified labels: TRUE, FALSE, character vector, or NULL.

nodes

Node data frame.

n

Number of nodes.

Value

Character vector of labels (or NULL for no labels).


Resolve Loop Rotation

Description

Determines rotation angle for self-loops.

Usage

resolve_loop_rotation(loopRotation, edges, layout = NULL)

Arguments

loopRotation

User-specified rotation(s) or NULL.

edges

Edge data frame.

layout

Layout coordinates (to auto-calculate optimal rotation).

Value

Vector of rotation angles in radians.


Resolve Node Colors

Description

Determines node colors from various inputs.

Usage

resolve_node_colors(
  color,
  n,
  nodes = NULL,
  groups = NULL,
  default_col = "#4A90D9"
)

Arguments

color

User-specified color(s) or NULL.

n

Number of nodes.

nodes

Node data frame (for group coloring).

groups

Group assignments for color mapping.

default_col

Default node color.

Value

Vector of colors for each node.


Resolve Node Sizes

Description

Converts vsize parameter to user coordinate sizes.

Usage

resolve_node_sizes(
  vsize,
  n,
  default_size = NULL,
  scale_factor = NULL,
  scaling = "default"
)

Arguments

vsize

User-specified node size(s).

n

Number of nodes.

default_size

Default size if NULL (uses scale constants if NULL).

scale_factor

Scale factor to apply (uses scale constants if NULL).

scaling

Scaling mode: "default" or "legacy".

Value

Vector of node sizes.


Resolve Shape Parameter

Description

Converts shape specification to vector of shape names.

Usage

resolve_shapes(shape, n)

Arguments

shape

Shape specification.

n

Number of nodes.

Value

Character vector of shape names.


Resolve Stars from Various Inputs

Description

Resolves significance stars from character vectors, logical, or p-values.

Usage

resolve_stars(stars_input, p_values = NULL, n)

Arguments

stars_input

User input: character vector, logical, or numeric p-values.

p_values

P-values for computing stars if stars_input is TRUE/numeric.

n

Number of edges.

Value

Character vector of stars.


Scaling Constants

Description

Central scaling constants for parameter alignment between splot/soplot.


Create an Alpha Scale

Description

Map values to transparency.

Usage

scale_alpha(values, range = c(0.3, 1))

Arguments

values

Values to map.

range

Output alpha range.

Value

Scaled values.


Create a Color Scale

Description

Map values to colors.

Usage

scale_color(values, palette = "viridis", limits = NULL)

Arguments

values

Values to map.

palette

Color palette (vector of colors or palette function name).

limits

Optional range limits.

Value

Character vector of colors.


Create a Categorical Color Scale

Description

Map categorical values to colors.

Usage

scale_color_discrete(values, palette = "colorblind")

Arguments

values

Categorical values.

palette

Color palette.

Value

Character vector of colors.


Scale Edge Widths Based on Weights

Description

Unified edge width scaling function that supports multiple scaling modes, two-tier cutoff system (like qgraph), and output range specification.

Usage

scale_edge_widths(
  weights,
  esize = NULL,
  n_nodes = NULL,
  directed = FALSE,
  mode = "linear",
  maximum = NULL,
  minimum = 0,
  cut = NULL,
  range = c(0.5, 4)
)

Arguments

weights

Numeric vector of edge weights.

esize

Base edge size. NULL uses adaptive sizing based on n_nodes.

n_nodes

Number of nodes (for adaptive esize calculation).

directed

Whether network is directed (affects adaptive esize).

mode

Scaling mode: "linear", "log", "sqrt", or "rank".

maximum

Max weight for normalization. NULL for auto-detect.

minimum

Min weight threshold. Edges below this get minimum width.

cut

Two-tier cutoff threshold. NULL = auto (75th percentile), 0 = disabled (continuous scaling), positive number = manual threshold.

range

Output width range as c(min_width, max_width).

Details

Scaling Modes

Two-Tier System (cut parameter)

When cut > 0, edges are divided into two tiers:

This matches qgraph's behavior where weak edges are visually de-emphasized.

Value

Numeric vector of scaled edge widths.


Scale Edge Widths (Simple Version)

Description

Simple linear edge width scaling used by sn_edges() when width="weight". For the full-featured version with multiple modes and cut parameter, see scale_edge_widths() in scale-constants.R.

Usage

scale_edge_widths_simple(values, range = c(0.5, 3), maximum = NULL)

Arguments

values

Numeric values to scale.

range

Target width range (min, max).

maximum

Optional maximum value for scaling. If provided, this value maps to the max of range, and values above it are capped.

Value

Scaled width values.


Scale Node Sizes

Description

Scale node sizes based on a numeric variable.

Usage

scale_node_sizes(values, range = c(0.03, 0.1))

Arguments

values

Numeric values to scale.

range

Target size range (min, max).

Value

Scaled size values.


Create a Size Scale

Description

Map values to sizes.

Usage

scale_size(values, range = c(0.03, 0.1), trans = "linear")

Arguments

values

Values to map.

range

Output size range.

trans

Transformation: "linear", "sqrt", "log".

Value

Scaled values.


Create a Width Scale

Description

Map values to line widths.

Usage

scale_width(values, range = c(0.5, 3))

Arguments

values

Values to map.

range

Output width range.

Value

Scaled values.


Set Edges in Cograph Network

Description

Replaces the edges in a cograph_network object. Expects a data frame with from, to, and optionally weight columns. Updates the from, to, weight vectors and n_edges.

Usage

set_edges(x, edges_df)

Arguments

x

A cograph_network object.

edges_df

A data frame with columns: from, to, and optionally weight.

Value

The modified cograph_network object.

See Also

as_cograph, get_edges, set_nodes

Examples

mat <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)
net <- as_cograph(mat)
new_edges <- data.frame(from = c(1, 2), to = c(2, 3), weight = c(0.5, 0.8))
net <- set_edges(net, new_edges)
get_edges(net)

Set Layout in Cograph Network

Description

Sets the layout coordinates in a cograph_network object. Updates the x and y columns in the nodes data frame.

Usage

set_layout(x, layout_df)

Arguments

x

A cograph_network object.

layout_df

A data frame with x and y columns, or a matrix with 2 columns.

Value

The modified cograph_network object.

See Also

as_cograph, get_nodes, sn_layout

Examples

mat <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)
net <- as_cograph(mat)
layout <- data.frame(x = c(0, 1, 0.5), y = c(0, 0, 1))
net <- set_layout(net, layout)
get_nodes(net)

Set Nodes in Cograph Network

Description

Replaces the nodes data frame in a cograph_network object. Automatically updates n_nodes and labels.

Usage

set_nodes(x, nodes_df)

Arguments

x

A cograph_network object.

nodes_df

A data frame with node information (id, label columns expected).

Value

The modified cograph_network object.

See Also

as_cograph, get_nodes, set_edges

Examples

mat <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)
net <- as_cograph(mat)
new_nodes <- data.frame(id = 1:3, label = c("A", "B", "C"))
net <- set_nodes(net, new_nodes)
get_labels(net)

Basic Node Shapes

Description

Basic node shape drawing functions.


Shape Registry Functions

Description

Functions for registering built-in shapes.


Special Node Shapes

Description

Special node shape drawing functions (ellipse, heart, star, pie).


Custom SVG Node Shapes

Description

Functions for rendering custom SVG shapes as nodes.


Calculate Shortened Edge Endpoint

Description

Calculates where to stop drawing an edge line so the arrow head doesn't overlap with the line.

Usage

shorten_edge_for_arrow(x1, y1, x2, y2, arrow_size)

Arguments

x1, y1

Start point.

x2, y2

End point (arrow tip).

arrow_size

Arrow size.

Value

List with x, y coordinates of shortened endpoint.


Set Edge Aesthetics

Description

Customize the visual appearance of edges in a network plot.

Usage

sn_edges(
  network,
  width = NULL,
  edge_size = NULL,
  esize = NULL,
  edge_width_range = NULL,
  edge_scale_mode = NULL,
  edge_cutoff = NULL,
  cut = NULL,
  color = NULL,
  edge_positive_color = NULL,
  positive_color = NULL,
  edge_negative_color = NULL,
  negative_color = NULL,
  alpha = NULL,
  style = NULL,
  curvature = NULL,
  arrow_size = NULL,
  show_arrows = NULL,
  maximum = NULL,
  width_scale = NULL,
  labels = NULL,
  label_size = NULL,
  label_color = NULL,
  label_position = NULL,
  label_offset = NULL,
  label_bg = NULL,
  label_bg_padding = NULL,
  label_fontface = NULL,
  label_border = NULL,
  label_border_color = NULL,
  label_underline = NULL,
  label_shadow = NULL,
  label_shadow_color = NULL,
  label_shadow_offset = NULL,
  label_shadow_alpha = NULL,
  bidirectional = NULL,
  loop_rotation = NULL,
  curve_shape = NULL,
  curve_pivot = NULL,
  curves = NULL,
  ci = NULL,
  ci_scale = NULL,
  ci_alpha = NULL,
  ci_color = NULL,
  ci_style = NULL,
  ci_arrows = NULL,
  ci_lower = NULL,
  ci_upper = NULL,
  label_style = NULL,
  label_template = NULL,
  label_digits = NULL,
  label_ci_format = NULL,
  label_p = NULL,
  label_p_digits = NULL,
  label_p_prefix = NULL,
  label_stars = NULL
)

Arguments

network

A cograph_network object, matrix, data.frame, or igraph object. Matrices and other inputs are auto-converted.

width

Edge width. Can be a single value, vector (per-edge), or "weight".

edge_size

Base edge size for weight scaling. NULL (default) uses adaptive sizing based on network size: 15 * exp(-n_nodes/90) + 1. Larger values = thicker edges.

esize

Deprecated. Use edge_size instead.

edge_width_range

Output width range as c(min, max) for weight-based scaling. Default c(0.5, 4). Edges are scaled to fit within this range.

edge_scale_mode

Scaling mode for edge weights: "linear" (default), "log" (for wide weight ranges), "sqrt" (moderate compression), or "rank" (equal visual spacing).

edge_cutoff

Two-tier cutoff for edge width scaling. NULL (default) = auto 75th percentile. 0 = disabled. Positive number = manual threshold.

cut

Deprecated. Use edge_cutoff instead.

color

Edge color. Can be a single color, vector, or "weight" for automatic coloring based on edge weights.

edge_positive_color

Color for positive edge weights.

positive_color

Deprecated. Use edge_positive_color instead.

edge_negative_color

Color for negative edge weights.

negative_color

Deprecated. Use edge_negative_color instead.

alpha

Edge transparency (0-1).

style

Line style: "solid", "dashed", "dotted", "longdash", "twodash".

curvature

Edge curvature amount (0 = straight).

arrow_size

Size of arrow heads for directed networks.

show_arrows

Logical. Show arrows? Default TRUE for directed networks.

maximum

Maximum edge weight for scaling width. Weights above this are capped. Similar to qgraph's maximum parameter.

width_scale

Scale factor for edge widths. Values > 1 make edges thicker, values < 1 make them thinner. Applied after all other width calculations.

labels

Edge labels. Can be TRUE (show weights), a vector, or column name.

label_size

Edge label text size.

label_color

Edge label text color.

label_position

Position along edge (0 = source, 0.5 = middle, 1 = target).

label_offset

Perpendicular offset from edge line.

label_bg

Background color for edge labels (default "white"). Set to NA for transparent.

label_bg_padding

Padding around label text as proportion of text size (default 0.3).

label_fontface

Font face: "plain", "bold", "italic", "bold.italic" (default "plain").

label_border

Border style: NULL (none), "rect", "rounded", "circle" (default NULL).

label_border_color

Border color for label border (default "gray50").

label_underline

Logical. Underline the label text? (default FALSE).

label_shadow

Logical. Enable drop shadow for labels? (default FALSE).

label_shadow_color

Color for label shadow (default "gray40").

label_shadow_offset

Offset distance for shadow in points (default 0.5).

label_shadow_alpha

Transparency for shadow (0-1, default 0.5).

bidirectional

Logical. Show arrows at both ends of edges?

loop_rotation

Angle in radians for self-loop direction (default: pi/2 = top).

curve_shape

Spline tension for curved edges (-1 to 1, default: 0).

curve_pivot

Pivot position along edge for curve control point (0-1, default: 0.5).

curves

Curve mode: FALSE (straight edges), "mutual" (only curve reciprocal pairs), or "force" (curve all edges). Default FALSE.

ci

Numeric vector of CI widths (0-1 scale). Larger values = more uncertainty.

ci_scale

Width multiplier for CI underlay thickness. Default 2.

ci_alpha

Transparency for CI underlay (0-1). Default 0.15.

ci_color

CI underlay color. NA (default) uses main edge color.

ci_style

Line type for CI underlay: 1=solid, 2=dashed, 3=dotted. Default 2.

ci_arrows

Logical: show arrows on CI underlay? Default FALSE.

ci_lower

Numeric vector of lower CI bounds for labels.

ci_upper

Numeric vector of upper CI bounds for labels.

label_style

Preset style: "none", "estimate", "full", "range", "stars".

label_template

Template with placeholders: {est}, {range}, {low}, {up}, {p}, {stars}.

label_digits

Decimal places for estimates in template. Default 2.

label_ci_format

CI format: "bracket" for ⁠[low, up]⁠ or "dash" for low-up.

label_p

Numeric vector of p-values for edges.

label_p_digits

Decimal places for p-values. Default 3.

label_p_prefix

Prefix for p-values. Default "p=".

label_stars

Stars for labels: character vector, TRUE (compute from p), or numeric (treated as p-values).

Details

Vectorization

Most aesthetic parameters can be specified as:

Weight-Based Styling

When color = "weight", edges are colored by sign:

When width = "weight", edge widths scale with absolute weight values, respecting the maximum parameter if set.

Edge Label Templates

For statistical output (e.g., regression coefficients with CIs), use templates:

Preset styles via label_style:

CI Underlays

Visualize uncertainty by drawing a wider, semi-transparent edge behind:

Value

Modified cograph_network object that can be piped to further customization functions or plotting functions.

See Also

sn_nodes for node customization, cograph for network creation, splot and soplot for plotting, sn_layout for layout algorithms, sn_theme for visual themes

Examples

adj <- matrix(c(0, 1, -0.5, 1, 0, 1, -0.5, 1, 0), nrow = 3)

# Basic: auto-style by weight
cograph(adj) |>
  sn_edges(width = "weight", color = "weight")

# Direct matrix input (auto-converted)
adj |> sn_edges(width = 2, color = "gray50")

# Custom positive/negative colors
cograph(adj) |>
  sn_edges(
    color = "weight",
    edge_positive_color = "darkblue",
    edge_negative_color = "darkred"
  ) |>
  splot()

# Edge labels showing weights
cograph(adj) |>
  sn_edges(labels = TRUE, label_size = 0.8) |>
  splot()

# Statistical output with CI template
# Suppose we have estimates, lower/upper CI bounds
estimates <- c(0.5, -0.3, 0.8)
ci_lo <- c(0.2, -0.6, 0.5)
ci_hi <- c(0.8, -0.1, 1.1)

cograph(adj) |>
  sn_edges(
    label_template = "{est} [{low}, {up}]",
    ci_lower = ci_lo,
    ci_upper = ci_hi,
    label_digits = 2
  ) |>
  splot()

# Curved edges for reciprocal pairs
cograph(adj) |>
  sn_edges(curves = "mutual", curvature = 0.3) |>
  splot()

Convert Network to ggplot2

Description

Convert a Cograph network visualization to a ggplot2 object for further customization and composability.

Usage

sn_ggplot(network, title = NULL)

Arguments

network

A cograph_network object, matrix, data.frame, or igraph object. Matrices and other inputs are auto-converted.

title

Optional plot title.

Value

A ggplot2 object.

Examples

adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)
# With cograph()
p <- cograph(adj) |> sn_ggplot()
print(p)

# Direct matrix input
p <- adj |> sn_ggplot()

# Further customization
p + ggplot2::labs(title = "My Network")

Apply Layout to Network

Description

Apply a layout algorithm to compute node positions.

Usage

sn_layout(network, layout, seed = 42, ...)

Arguments

network

A cograph_network object, matrix, data.frame, or igraph object. Matrices and other inputs are auto-converted.

layout

Layout algorithm name or a CographLayout object.

seed

Random seed for deterministic layouts. Default 42. Set NULL for random.

...

Additional arguments passed to the layout function.

Details

Built-in Layouts

spring

Force-directed layout (Fruchterman-Reingold style). Good general-purpose layout. Default.

circle

Nodes arranged in a circle. Good for small networks or when structure is less important.

groups

Circular layout with grouped nodes clustered together.

grid

Nodes in a regular grid.

random

Random positions. Useful as starting point.

star

Central node with others arranged around it.

bipartite

Two-column layout for bipartite networks.

igraph Layouts

Two-letter codes for igraph layouts: "kk" (Kamada-Kawai), "fr" (Fruchterman-Reingold), "drl", "mds", "ni" (nicely), "tr" (tree), "ci" (circle), etc.

You can also pass igraph layout functions directly or use full names like "layout_with_kk".

Value

Modified cograph_network object.

See Also

cograph for network creation, sn_nodes for node customization, sn_edges for edge customization, sn_theme for visual themes, splot and soplot for plotting

Examples

adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)

# Built-in layouts
cograph(adj) |> sn_layout("circle") |> splot()
cograph(adj) |> sn_layout("spring") |> splot()

# igraph layouts (if igraph installed)
if (requireNamespace("igraph", quietly = TRUE)) {
  cograph(adj) |> sn_layout("kk") |> splot()
  cograph(adj) |> sn_layout("fr") |> splot()
}

# Custom coordinates
coords <- matrix(c(0, 0, 1, 0, 0.5, 1), ncol = 2, byrow = TRUE)
cograph(adj) |> sn_layout(coords) |> splot()

# Direct matrix input (auto-converts)
adj |> sn_layout("circle")

Set Node Aesthetics

Description

Customize the visual appearance of nodes in a network plot.

Usage

sn_nodes(
  network,
  size = NULL,
  shape = NULL,
  node_svg = NULL,
  svg_preserve_aspect = NULL,
  fill = NULL,
  border_color = NULL,
  border_width = NULL,
  alpha = NULL,
  label_size = NULL,
  label_color = NULL,
  label_position = NULL,
  show_labels = NULL,
  pie_values = NULL,
  pie_colors = NULL,
  pie_border_width = NULL,
  donut_fill = NULL,
  donut_values = NULL,
  donut_color = NULL,
  donut_colors = NULL,
  donut_border_width = NULL,
  donut_inner_ratio = NULL,
  donut_bg_color = NULL,
  donut_shape = NULL,
  donut_show_value = NULL,
  donut_value_size = NULL,
  donut_value_color = NULL,
  donut_value_fontface = NULL,
  donut_value_fontfamily = NULL,
  donut_value_digits = NULL,
  donut_value_prefix = NULL,
  donut_value_suffix = NULL,
  donut_value_format = NULL,
  donut2_values = NULL,
  donut2_colors = NULL,
  donut2_inner_ratio = NULL,
  label_fontface = NULL,
  label_fontfamily = NULL,
  label_hjust = NULL,
  label_vjust = NULL,
  label_angle = NULL,
  node_names = NULL
)

Arguments

network

A cograph_network object, matrix, data.frame, or igraph object. Matrices and other inputs are auto-converted.

size

Node size. Can be a single value, vector (per-node), or column name.

shape

Node shape. Options: "circle", "square", "triangle", "diamond", "pentagon", "hexagon", "ellipse", "heart", "star", "pie", "donut", "cross", "rectangle", or any custom SVG shape registered with register_svg_shape().

node_svg

Custom SVG for node shape: path to SVG file OR inline SVG string. Overrides shape parameter when provided.

svg_preserve_aspect

Logical: maintain SVG aspect ratio? Default TRUE.

fill

Node fill color. Can be a single color, vector, or column name.

border_color

Node border color.

border_width

Node border width.

alpha

Node transparency (0-1).

label_size

Label text size.

label_color

Label text color.

label_position

Label position: "center", "above", "below", "left", "right".

show_labels

Logical. Show node labels? Default TRUE.

pie_values

For pie shape: list or matrix of values for pie segments. Each element corresponds to a node and contains values for its segments.

pie_colors

For pie shape: colors for pie segments.

pie_border_width

Border width for pie chart nodes.

donut_fill

For donut shape: numeric value (0-1) specifying fill proportion. 0.1 = 10% filled, 0.5 = 50% filled, 1.0 = fully filled ring. Can be a single value (all nodes) or vector (per-node values).

donut_values

Deprecated. Use donut_fill for simple fill proportion. Still works for backwards compatibility.

donut_color

For donut shape: fill color(s) for the donut ring. Single color sets fill for all nodes. Two colors set fill and background for all nodes. More than 2 colors set per-node fill colors (recycled to n_nodes). Default: "lightgray" fill, "gray90" background when shape="donut".

donut_colors

Deprecated. Use donut_color instead.

donut_border_width

Border width for donut chart nodes.

donut_inner_ratio

For donut shape: inner radius ratio (0-1). Default 0.5.

donut_bg_color

For donut shape: background color for unfilled portion.

donut_shape

For donut: base shape for ring ("circle", "square", "hexagon", "triangle", "diamond", "pentagon"). Default "circle".

donut_show_value

For donut shape: show value in center? Default FALSE.

donut_value_size

For donut shape: font size for center value.

donut_value_color

For donut shape: color for center value text.

donut_value_fontface

For donut shape: font face for center value ("plain", "bold", "italic", "bold.italic"). Default "bold".

donut_value_fontfamily

For donut shape: font family for center value ("sans", "serif", "mono"). Default "sans".

donut_value_digits

For donut shape: decimal places for value display. Default 2.

donut_value_prefix

For donut shape: text before value (e.g., "$"). Default "".

donut_value_suffix

For donut shape: text after value (e.g., "%"). Default "".

donut_value_format

For donut shape: custom format function (overrides digits).

donut2_values

For double donut: list of values for inner donut ring.

donut2_colors

For double donut: colors for inner donut ring segments.

donut2_inner_ratio

For double donut: inner radius ratio for inner donut ring. Default 0.4.

label_fontface

Font face for node labels: "plain", "bold", "italic", "bold.italic". Default "plain".

label_fontfamily

Font family for node labels: "sans", "serif", "mono", or system font. Default "sans".

label_hjust

Horizontal justification for node labels (0=left, 0.5=center, 1=right). Default 0.5.

label_vjust

Vertical justification for node labels (0=bottom, 0.5=center, 1=top). Default 0.5.

label_angle

Text rotation angle in degrees for node labels. Default 0.

node_names

Alternative names for legend (separate from display labels).

Details

Vectorization

All aesthetic parameters can be specified as:

Parameters are validated for correct length; providing a vector with length other than 1 or n_nodes will produce a warning about recycling.

Donut Charts

Donut charts are ideal for showing a single proportion (0-1) per node:

Value

Modified cograph_network object that can be piped to further customization functions or plotting functions.

See Also

sn_edges for edge customization, cograph for network creation, splot and soplot for plotting, sn_layout for layout algorithms, sn_theme for visual themes

Examples

adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)

# Basic usage with cograph()
cograph(adj) |>
  sn_nodes(size = 0.08, fill = "steelblue", shape = "circle")

# Direct matrix input (auto-converted)
adj |> sn_nodes(fill = "coral", size = 0.1)

# Per-node customization with vectors
cograph(adj) |>
  sn_nodes(
    size = c(0.08, 0.06, 0.1),
    fill = c("red", "blue", "green"),
    label_position = c("above", "below", "center")
  ) |>
  splot()

# Donut chart nodes showing proportions
cograph(adj) |>
  sn_nodes(
    donut_fill = c(0.25, 0.75, 0.5),
    donut_color = "steelblue",
    donut_show_value = TRUE,
    donut_value_suffix = "%"
  ) |>
  splot()

# Mixed shapes per node
cograph(adj) |>
  sn_nodes(
    shape = c("circle", "square", "triangle"),
    fill = c("#E41A1C", "#377EB8", "#4DAF4A")
  ) |>
  splot()

Apply Color Palette to Network

Description

Apply a color palette for node and/or edge coloring.

Usage

sn_palette(network, palette, target = "nodes", by = NULL)

Arguments

network

A cograph_network object, matrix, data.frame, or igraph object. Matrices and other inputs are auto-converted.

palette

Palette name or function.

target

What to apply the palette to: "nodes", "edges", or "both".

by

Variable to map colors to (for nodes: column name or "group").

Details

Available Palettes

Use list_palettes() to see all available palettes. Common options:

viridis

Perceptually uniform, colorblind-friendly.

colorblind

Optimized for color vision deficiency.

pastel

Soft, muted colors.

bright

Saturated, vivid colors.

grayscale

Shades of gray.

You can also pass a custom palette function that takes n and returns n colors.

Value

Modified cograph_network object.

See Also

cograph for network creation, sn_theme for visual themes, sn_nodes for node customization, list_palettes to see available palettes, splot and soplot for plotting

Examples

adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)

# Apply palette to nodes
cograph(adj) |> sn_palette("viridis") |> splot()

# Apply to edges
cograph(adj) |> sn_palette("colorblind", target = "edges") |> splot()

# Apply to both
cograph(adj) |> sn_palette("pastel", target = "both") |> splot()

# Custom palette function
my_pal <- function(n) rainbow(n, s = 0.7)
cograph(adj) |> sn_palette(my_pal) |> splot()

# Direct matrix input
adj |> sn_palette("viridis")

Save Network Visualization

Description

Save a Cograph network visualization to a file.

Usage

sn_save(network, filename, width = 7, height = 7, dpi = 300, title = NULL, ...)

Arguments

network

A cograph_network object, matrix, data.frame, or igraph object. Matrices and other inputs are auto-converted.

filename

Output filename. Format is detected from extension.

width

Width in inches (default 7).

height

Height in inches (default 7).

dpi

Resolution for raster formats (default 300).

title

Optional plot title.

...

Additional arguments passed to the graphics device.

Value

Invisible filename.

Examples


adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)
# With cograph()
net <- cograph(adj)
sn_save(net, file.path(tempdir(), "network.pdf"))

# Direct matrix input
sn_save(adj, file.path(tempdir(), "network.png"), dpi = 300)


Save as ggplot2

Description

Save network as a ggplot2 object to file using ggsave.

Usage

sn_save_ggplot(
  network,
  filename,
  width = 7,
  height = 7,
  dpi = 300,
  title = NULL,
  ...
)

Arguments

network

A cograph_network object.

filename

Output filename.

width

Width in inches.

height

Height in inches.

dpi

Resolution for raster formats.

title

Optional plot title.

...

Additional arguments passed to ggsave.

Value

Invisible filename.

Examples


adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)
net <- cograph(adj)
sn_save_ggplot(net, file.path(tempdir(), "network.pdf"))


Apply Theme to Network

Description

Apply a visual theme to the network.

Usage

sn_theme(network, theme, ...)

Arguments

network

A cograph_network object, matrix, data.frame, or igraph object. Matrices and other inputs are auto-converted.

theme

Theme name (string) or CographTheme object.

...

Additional theme parameters to override.

Details

Available Themes

classic

Default theme with white background, blue nodes, gray edges.

dark

Dark background with light nodes. Good for presentations.

minimal

Subtle styling with thin edges and muted colors.

colorblind

Optimized for color vision deficiency.

grayscale

Black and white only.

vibrant

Bold, saturated colors.

Use list_themes() to see all available themes.

Value

Modified cograph_network object.

See Also

cograph for network creation, sn_palette for color palettes, sn_nodes for node customization, sn_edges for edge customization, list_themes to see available themes, splot and soplot for plotting

Examples

adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)

# Apply different themes
cograph(adj) |> sn_theme("dark") |> splot()
cograph(adj) |> sn_theme("minimal") |> splot()

# Override specific theme properties
cograph(adj) |> sn_theme("classic", background = "lightgray") |> splot()

# Direct matrix input
adj |> sn_theme("dark")

qgraph-Compatible Geometry Utilities

Description

Coordinate transformation and geometry functions that exactly replicate qgraph's visual logic. Used by splot() for qgraph-compatible network visualization.


Plot Cograph Network

Description

Main plotting function for Cograph networks. Renders the network visualization using grid graphics. Accepts all node and edge aesthetic parameters.

Usage

soplot(
  network,
  title = NULL,
  title_size = 14,
  margins = c(0.05, 0.05, 0.1, 0.05),
  layout_margin = 0.15,
  newpage = TRUE,
  layout = NULL,
  theme = NULL,
  seed = 42,
  labels = NULL,
  threshold = NULL,
  maximum = NULL,
  node_size = NULL,
  node_shape = NULL,
  node_fill = NULL,
  node_border_color = NULL,
  node_border_width = NULL,
  node_alpha = NULL,
  label_size = NULL,
  label_color = NULL,
  label_position = NULL,
  show_labels = NULL,
  pie_values = NULL,
  pie_colors = NULL,
  pie_border_width = NULL,
  donut_values = NULL,
  donut_border_width = NULL,
  donut_inner_ratio = NULL,
  donut_bg_color = NULL,
  donut_show_value = NULL,
  donut_value_size = NULL,
  donut_value_color = NULL,
  donut_fill = NULL,
  donut_color = NULL,
  donut_colors = NULL,
  donut_shape = "circle",
  donut_value_fontface = "bold",
  donut_value_fontfamily = "sans",
  donut_value_digits = 2,
  donut_value_prefix = "",
  donut_value_suffix = "",
  donut2_values = NULL,
  donut2_colors = NULL,
  donut2_inner_ratio = 0.4,
  edge_width = NULL,
  edge_size = NULL,
  esize = NULL,
  edge_width_range = NULL,
  edge_scale_mode = "linear",
  edge_cutoff = NULL,
  cut = NULL,
  edge_width_scale = NULL,
  edge_color = NULL,
  edge_alpha = NULL,
  edge_style = NULL,
  curvature = NULL,
  arrow_size = NULL,
  show_arrows = NULL,
  edge_positive_color = NULL,
  positive_color = NULL,
  edge_negative_color = NULL,
  negative_color = NULL,
  edge_duplicates = NULL,
  edge_labels = NULL,
  edge_label_size = NULL,
  edge_label_color = NULL,
  edge_label_position = NULL,
  edge_label_offset = NULL,
  edge_label_bg = NULL,
  edge_label_fontface = NULL,
  edge_label_border = NULL,
  edge_label_border_color = NULL,
  edge_label_underline = NULL,
  bidirectional = NULL,
  loop_rotation = NULL,
  curve_shape = NULL,
  curve_pivot = NULL,
  curves = NULL,
  node_names = NULL,
  legend = FALSE,
  legend_position = "topright",
  scaling = "default",
  weight_digits = 2
)

sn_render(
  network,
  title = NULL,
  title_size = 14,
  margins = c(0.05, 0.05, 0.1, 0.05),
  layout_margin = 0.15,
  newpage = TRUE,
  layout = NULL,
  theme = NULL,
  seed = 42,
  labels = NULL,
  threshold = NULL,
  maximum = NULL,
  node_size = NULL,
  node_shape = NULL,
  node_fill = NULL,
  node_border_color = NULL,
  node_border_width = NULL,
  node_alpha = NULL,
  label_size = NULL,
  label_color = NULL,
  label_position = NULL,
  show_labels = NULL,
  pie_values = NULL,
  pie_colors = NULL,
  pie_border_width = NULL,
  donut_values = NULL,
  donut_border_width = NULL,
  donut_inner_ratio = NULL,
  donut_bg_color = NULL,
  donut_show_value = NULL,
  donut_value_size = NULL,
  donut_value_color = NULL,
  donut_fill = NULL,
  donut_color = NULL,
  donut_colors = NULL,
  donut_shape = "circle",
  donut_value_fontface = "bold",
  donut_value_fontfamily = "sans",
  donut_value_digits = 2,
  donut_value_prefix = "",
  donut_value_suffix = "",
  donut2_values = NULL,
  donut2_colors = NULL,
  donut2_inner_ratio = 0.4,
  edge_width = NULL,
  edge_size = NULL,
  esize = NULL,
  edge_width_range = NULL,
  edge_scale_mode = "linear",
  edge_cutoff = NULL,
  cut = NULL,
  edge_width_scale = NULL,
  edge_color = NULL,
  edge_alpha = NULL,
  edge_style = NULL,
  curvature = NULL,
  arrow_size = NULL,
  show_arrows = NULL,
  edge_positive_color = NULL,
  positive_color = NULL,
  edge_negative_color = NULL,
  negative_color = NULL,
  edge_duplicates = NULL,
  edge_labels = NULL,
  edge_label_size = NULL,
  edge_label_color = NULL,
  edge_label_position = NULL,
  edge_label_offset = NULL,
  edge_label_bg = NULL,
  edge_label_fontface = NULL,
  edge_label_border = NULL,
  edge_label_border_color = NULL,
  edge_label_underline = NULL,
  bidirectional = NULL,
  loop_rotation = NULL,
  curve_shape = NULL,
  curve_pivot = NULL,
  curves = NULL,
  node_names = NULL,
  legend = FALSE,
  legend_position = "topright",
  scaling = "default",
  weight_digits = 2
)

Arguments

network

A cograph_network object, matrix, data.frame, or igraph object. Matrices and other inputs are auto-converted.

title

Optional plot title.

title_size

Title font size.

margins

Plot margins as c(bottom, left, top, right).

layout_margin

Margin around the network layout (proportion of viewport). Default 0.15.

newpage

Logical. Start a new graphics page? Default TRUE.

layout

Layout algorithm. Built-in: "circle", "spring", "groups", "grid", "random", "star", "bipartite". igraph (2-letter): "kk" (Kamada-Kawai), "fr" (Fruchterman-Reingold), "drl", "mds", "ni" (nicely), "tr" (tree), etc. Can also pass a coordinate matrix or igraph layout function directly.

theme

Theme name: "classic", "dark", "minimal", etc.

seed

Random seed for deterministic layouts. Default 42. Set NULL for random.

labels

Node labels. Can be a character vector to set custom labels.

threshold

Minimum absolute edge weight to display. Edges with abs(weight) < threshold are hidden. Similar to qgraph's threshold.

maximum

Maximum edge weight for width scaling. Weights above this are capped. Similar to qgraph's maximum parameter.

node_size

Node size.

node_shape

Node shape: "circle", "square", "triangle", "diamond", "ellipse", "heart", "star", "pie", "donut", "cross".

node_fill

Node fill color.

node_border_color

Node border color.

node_border_width

Node border width.

node_alpha

Node transparency (0-1).

label_size

Node label text size.

label_color

Node label text color.

label_position

Label position: "center", "above", "below", "left", "right".

show_labels

Logical. Show node labels?

pie_values

For pie/donut/donut_pie nodes: list or matrix of values for segments. For donut with single value (0-1), shows that proportion filled.

pie_colors

For pie/donut/donut_pie nodes: colors for pie segments.

pie_border_width

Border width for pie chart segments.

donut_values

For donut_pie nodes: vector of values (0-1) for outer ring proportion.

donut_border_width

Border width for donut ring.

donut_inner_ratio

For donut nodes: inner radius ratio (0-1). Default 0.5.

donut_bg_color

For donut nodes: background color for unfilled portion.

donut_show_value

For donut nodes: show value in center? Default FALSE.

donut_value_size

For donut nodes: font size for center value.

donut_value_color

For donut nodes: color for center value text.

donut_fill

Numeric value (0-1) for donut fill proportion. This is the simplified API for creating donut charts. Can be a single value or vector per node.

donut_color

Fill color(s) for the donut ring. Simplified API: single color for fill, or c(fill, background) for both.

donut_colors

Deprecated. Use donut_color instead.

donut_shape

Base shape for donut: "circle", "square", "hexagon", "triangle", "diamond", "pentagon". Default inherits from node_shape.

donut_value_fontface

Font face for donut center value: "plain", "bold", "italic", "bold.italic". Default "bold".

donut_value_fontfamily

Font family for donut center value. Default "sans".

donut_value_digits

Decimal places for donut center value. Default 2.

donut_value_prefix

Text before donut center value (e.g., "$"). Default "".

donut_value_suffix

Text after donut center value (e.g., "%"). Default "".

donut2_values

List of values for inner donut ring (for double donut).

donut2_colors

List of color vectors for inner donut ring segments.

donut2_inner_ratio

Inner radius ratio for inner donut ring. Default 0.4.

edge_width

Edge width. If NULL, scales by weight using edge_size and edge_width_range.

edge_size

Base edge size for weight scaling. NULL (default) uses adaptive sizing based on network size: 15 * exp(-n_nodes/90) + 1. Larger values = thicker edges.

esize

Deprecated. Use edge_size instead.

edge_width_range

Output width range as c(min, max) for weight-based scaling. Default c(0.5, 4). Edges are scaled to fit within this range.

edge_scale_mode

Scaling mode for edge weights: "linear" (default), "log" (for wide weight ranges), "sqrt" (moderate compression), or "rank" (equal visual spacing).

edge_cutoff

Two-tier cutoff for edge width scaling. NULL (default) = auto 75th percentile. 0 = disabled. Positive number = manual threshold.

cut

Deprecated. Use edge_cutoff instead.

edge_width_scale

Scale factor for edge widths. Values > 1 make edges thicker.

edge_color

Edge color.

edge_alpha

Edge transparency (0-1).

edge_style

Line style: "solid", "dashed", "dotted".

curvature

Edge curvature amount.

arrow_size

Size of arrow heads.

show_arrows

Logical. Show arrows?

edge_positive_color

Color for positive edge weights.

positive_color

Deprecated. Use edge_positive_color instead.

edge_negative_color

Color for negative edge weights.

negative_color

Deprecated. Use edge_negative_color instead.

edge_duplicates

How to handle duplicate edges in undirected networks. NULL (default) = stop with error listing duplicates. Options: "sum", "mean", "first", "max", "min", or a custom aggregation function.

edge_labels

Edge labels. Can be TRUE to show weights, or a vector.

edge_label_size

Edge label text size.

edge_label_color

Edge label text color.

edge_label_position

Position along edge (0 = source, 0.5 = middle, 1 = target).

edge_label_offset

Perpendicular offset from edge line.

edge_label_bg

Background color for edge labels (default "white"). Set to NA for transparent.

edge_label_fontface

Font face: "plain", "bold", "italic", "bold.italic".

edge_label_border

Border style: NULL, "rect", "rounded", "circle".

edge_label_border_color

Border color for label border.

edge_label_underline

Logical. Underline the label text?

bidirectional

Logical. Show arrows at both ends of edges?

loop_rotation

Angle in radians for self-loop direction (default: pi/2 = top).

curve_shape

Spline tension for curved edges (-1 to 1, default: 0).

curve_pivot

Pivot position along edge for curve control point (0-1, default: 0.5).

curves

Curve mode: TRUE (default) = single edges straight, reciprocal edges curve as ellipse (two opposing curves); FALSE = all straight; "force" = all curved.

node_names

Alternative names for legend (separate from display labels).

legend

Logical. Show legend?

legend_position

Legend position: "topright", "topleft", "bottomright", "bottomleft".

scaling

Scaling mode: "default" for qgraph-matched scaling where node_size=6 looks similar to qgraph vsize=6, or "legacy" to preserve pre-v2.0 behavior.

weight_digits

Number of decimal places to round edge weights to before plotting. Edges that round to zero are automatically removed. Default 2. Set NULL to disable rounding.

Details

soplot vs splot

soplot() uses grid graphics while splot() uses base R graphics. Both accept the same parameters and produce visually similar output. Choose based on:

Edge Curve Behavior

Edge curving is controlled by the curves and curvature parameters:

curves = FALSE

All edges are straight lines.

curves = TRUE

(Default) Reciprocal edge pairs (A->B and B->A) curve in opposite directions to form a visual ellipse. Single edges remain straight.

curves = "force"

All edges curve inward toward the network center.

Weight Scaling Modes (edge_scale_mode)

Controls how edge weights map to visual widths:

linear

Width proportional to weight. Best for similar-magnitude weights.

log

Logarithmic scaling. Best for weights spanning orders of magnitude.

sqrt

Square root scaling. Moderate compression for skewed data.

rank

Rank-based scaling. Equal visual spacing regardless of values.

Donut Visualization

The donut system visualizes proportions (0-1) as filled rings around nodes:

donut_fill

Proportion filled (0-1). Can be scalar or per-node vector.

donut_color

Fill color. Single color, c(fill, bg), or per-node vector.

donut_shape

Base shape: "circle", "square", "hexagon", etc.

donut_show_value

Show numeric value in center.

Value

Invisible NULL. Called for side effect of drawing.

See Also

splot for base R graphics rendering (alternative engine), cograph for creating network objects, sn_nodes for node customization, sn_edges for edge customization, sn_layout for layout algorithms, sn_theme for visual themes, from_qgraph and from_tna for converting external objects

Examples

adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), nrow = 3)
# With cograph()
cograph(adj) |> soplot()

# Direct matrix input with all options
adj |> soplot(
  layout = "circle",
  node_fill = "steelblue",
  node_size = 0.08,
  edge_width = 2
)

Base R Graphics Network Plotting

Description

Network visualization using base R graphics (similar to qgraph).

Creates a network visualization using base R graphics functions (polygon, lines, xspline, etc.) instead of grid graphics. This provides better performance for large networks and uses the same snake_case parameter names as soplot() for consistency.

Usage

splot(
  x,
  layout = "oval",
  directed = NULL,
  seed = 42,
  theme = NULL,
  node_size = NULL,
  node_size2 = NULL,
  node_shape = "circle",
  node_svg = NULL,
  svg_preserve_aspect = TRUE,
  node_fill = NULL,
  node_border_color = NULL,
  node_border_width = 1,
  node_alpha = 1,
  labels = TRUE,
  label_size = NULL,
  label_color = "black",
  label_position = "center",
  label_fontface = "plain",
  label_fontfamily = "sans",
  label_hjust = 0.5,
  label_vjust = 0.5,
  label_angle = 0,
  pie_values = NULL,
  pie_colors = NULL,
  pie_border_width = NULL,
  donut_fill = NULL,
  donut_values = NULL,
  donut_color = NULL,
  donut_colors = NULL,
  donut_border_color = NULL,
  donut_border_width = NULL,
  donut_outer_border_color = NULL,
  donut_line_type = "solid",
  donut_border_lty = NULL,
  donut_inner_ratio = 0.8,
  donut_bg_color = "gray90",
  donut_shape = "circle",
  donut_show_value = FALSE,
  donut_value_size = 0.8,
  donut_value_color = "black",
  donut_value_fontface = "bold",
  donut_value_fontfamily = "sans",
  donut_value_digits = 2,
  donut_value_prefix = "",
  donut_value_suffix = "",
  donut_empty = TRUE,
  donut2_values = NULL,
  donut2_colors = NULL,
  donut2_inner_ratio = 0.4,
  edge_color = NULL,
  edge_width = NULL,
  edge_size = NULL,
  esize = NULL,
  edge_width_range = c(0.1, 4),
  edge_scale_mode = "linear",
  edge_cutoff = NULL,
  cut = NULL,
  edge_alpha = 0.8,
  edge_labels = FALSE,
  edge_label_size = 0.8,
  edge_label_color = "gray30",
  edge_label_bg = "white",
  edge_label_position = 0.5,
  edge_label_offset = 0,
  edge_label_fontface = "plain",
  edge_label_shadow = FALSE,
  edge_label_shadow_color = "gray40",
  edge_label_shadow_offset = 0.5,
  edge_label_shadow_alpha = 0.5,
  edge_style = 1,
  curvature = 0,
  curve_scale = TRUE,
  curve_shape = 0,
  curve_pivot = 0.5,
  curves = TRUE,
  arrow_size = 1,
  arrow_angle = pi/6,
  show_arrows = TRUE,
  bidirectional = FALSE,
  loop_rotation = NULL,
  edge_start_style = "solid",
  edge_start_length = 0.15,
  edge_start_dot_density = "12",
  edge_ci = NULL,
  edge_ci_scale = 2,
  edge_ci_alpha = 0.15,
  edge_ci_color = NA,
  edge_ci_style = 2,
  edge_ci_arrows = FALSE,
  edge_label_style = "none",
  edge_label_template = NULL,
  edge_label_digits = 2,
  edge_label_oneline = TRUE,
  edge_label_ci_format = "bracket",
  edge_ci_lower = NULL,
  edge_ci_upper = NULL,
  edge_label_p = NULL,
  edge_label_p_digits = 3,
  edge_label_p_prefix = "p=",
  edge_label_stars = NULL,
  weight_digits = 2,
  threshold = 0,
  minimum = 0,
  maximum = NULL,
  edge_positive_color = "#2E7D32",
  positive_color = NULL,
  edge_negative_color = "#C62828",
  negative_color = NULL,
  edge_duplicates = NULL,
  title = NULL,
  title_size = 1.2,
  margins = c(0.1, 0.1, 0.1, 0.1),
  background = "white",
  rescale = TRUE,
  layout_scale = 1,
  layout_margin = 0.15,
  aspect = TRUE,
  use_pch = FALSE,
  usePCH = NULL,
  scaling = "default",
  legend = FALSE,
  legend_position = "topright",
  legend_size = 0.8,
  legend_edge_colors = TRUE,
  legend_node_sizes = FALSE,
  groups = NULL,
  node_names = NULL,
  filetype = "default",
  filename = file.path(tempdir(), "splot"),
  width = 7,
  height = 7,
  res = 600,
  ...
)

Arguments

x

Network input. Can be:

  • A square numeric matrix (adjacency/weight matrix)

  • A data frame with edge list (from, to, optional weight columns)

  • An igraph object

  • A cograph_network object

layout

Layout algorithm: "circle", "spring", "groups", or a matrix of x,y coordinates, or an igraph layout function. Also supports igraph two-letter codes: "kk", "fr", "drl", "mds", "ni", etc. Default is "oval"

directed

Logical. Force directed interpretation. NULL for auto-detect.

seed

Random seed for deterministic layouts. Default 42.

theme

Theme name: "classic", "dark", "minimal", "colorblind", etc.

node_size

Node size(s). Single value or vector. Default 3.

node_size2

Secondary node size for ellipse/rectangle height.

node_shape

Node shape(s): "circle", "square", "triangle", "diamond", "pentagon", "hexagon", "star", "heart", "ellipse", "cross", or any custom SVG shape registered with register_svg_shape().

node_svg

Custom SVG for nodes: path to SVG file OR inline SVG string.

svg_preserve_aspect

Logical: maintain SVG aspect ratio? Default TRUE.

node_fill

Node fill color(s).

node_border_color

Node border color(s).

node_border_width

Node border width(s).

node_alpha

Node transparency (0-1). Default 1.

labels

Node labels: TRUE (use node names/indices), FALSE (none), or character vector.

label_size

Label character expansion factor.

label_color

Label text color.

label_position

Label position: "center", "above", "below", "left", "right".

label_fontface

Font face for labels: "plain", "bold", "italic", "bold.italic". Default "plain".

label_fontfamily

Font family for labels: "sans", "serif", "mono". Default "sans".

label_hjust

Horizontal justification (0=left, 0.5=center, 1=right). Default 0.5.

label_vjust

Vertical justification (0=bottom, 0.5=center, 1=top). Default 0.5.

label_angle

Text rotation angle in degrees. Default 0.

pie_values

List of numeric vectors for pie chart nodes. Each element corresponds to a node and contains values for pie segments. If a simple numeric vector with values between 0 and 1 is provided (e.g., centrality scores), it is automatically converted to donut_fill for convenience.

pie_colors

List of color vectors for pie segments.

pie_border_width

Border width for pie slice dividers. NULL uses node_border_width.

donut_fill

Numeric value (0-1) for donut fill proportion. This is the qgraph-style API: 0.1 = 10% filled, 0.5 = 50% filled, 1.0 = fully filled. Can be a single value (all nodes) or vector (per-node values).

donut_values

Deprecated. Use donut_fill for simple fill proportion.

donut_color

Fill color(s) for the donut ring. Single color sets fill for all nodes. Two colors set fill and background for all nodes. More than 2 colors set per-node fill colors (recycled to n_nodes). Default: "maroon" fill, "gray90" background when node_shape="donut".

donut_colors

Deprecated. Use donut_color instead.

donut_border_color

Border color for donut rings. NULL uses node_border_color.

donut_border_width

Border width for donut rings. NULL uses node_border_width.

donut_outer_border_color

Color for outer boundary border (enables double border). NULL (default) shows single border. Set to a color for double border effect. Can be scalar or per-node vector.

donut_line_type

Line type for donut borders: "solid", "dashed", "dotted", or numeric (1=solid, 2=dashed, 3=dotted). Can be scalar or per-node vector.

donut_border_lty

Deprecated. Use donut_line_type instead.

donut_inner_ratio

Inner radius ratio for donut (0-1). Default 0.5.

donut_bg_color

Background color for unfilled donut portion.

donut_shape

Base shape for donut: "circle", "square", "hexagon", "triangle", "diamond", "pentagon". Can be a single value or per-node vector. Default inherits from node_shape (e.g., hexagon nodes get hexagon donuts). Set explicitly to override (e.g., donut_shape = "hexagon" for hexagon donuts on all nodes regardless of node_shape).

donut_show_value

Logical: show value in donut center? Default FALSE.

donut_value_size

Font size for donut center value.

donut_value_color

Color for donut center value.

donut_value_fontface

Font face for donut center value: "plain", "bold", "italic", "bold.italic". Default "bold".

donut_value_fontfamily

Font family for donut center value: "sans", "serif", "mono". Default "sans".

donut_value_digits

Decimal places for donut center value. Default 2.

donut_value_prefix

Text before donut center value (e.g., "$"). Default "".

donut_value_suffix

Text after donut center value (e.g., "%"). Default "".

donut_empty

Logical: render empty donut rings for NA values? Default TRUE.

donut2_values

List of values for inner donut ring (for double donut).

donut2_colors

List of color vectors for inner donut ring segments.

donut2_inner_ratio

Inner radius ratio for inner donut ring. Default 0.4.

edge_color

Edge color(s). If NULL, uses edge_positive_color/edge_negative_color based on weight.

edge_width

Edge width(s). If NULL, scales by weight using edge_size and edge_width_range.

edge_size

Base edge size for weight scaling. NULL (default) uses adaptive sizing based on network size: 15 * exp(-n_nodes/90) + 1. For directed networks, this is halved. Larger values = thicker edges overall.

esize

Deprecated. Use edge_size instead.

edge_width_range

Output width range as c(min, max) for weight-based scaling. Default c(0.5, 4). Edges are scaled to fit within this range.

edge_scale_mode

Scaling mode for edge weights: "linear" (default, qgraph-style), "log" (logarithmic for wide weight ranges), "sqrt" (moderate compression), or "rank" (equal visual spacing regardless of weight distribution).

edge_cutoff

Two-tier cutoff for edge width scaling. NULL (default) = auto-calculate as 75th percentile of weights (qgraph behavior). 0 = disabled (continuous scaling). Positive number = manual threshold. Edges below cutoff get minimal width variation.

cut

Deprecated. Use edge_cutoff instead.

edge_alpha

Edge transparency (0-1). Default 0.8.

edge_labels

Edge labels: TRUE (show weights), FALSE (none), or character vector.

edge_label_size

Edge label size.

edge_label_color

Edge label text color.

edge_label_bg

Edge label background color.

edge_label_position

Position along edge (0-1).

edge_label_offset

Perpendicular offset for edge labels (0 = on line, positive = above).

edge_label_fontface

Font face: "plain", "bold", "italic", "bold.italic".

edge_label_shadow

Logical: enable drop shadow for edge labels? Default FALSE.

edge_label_shadow_color

Color for edge label shadow. Default "gray40".

edge_label_shadow_offset

Offset distance for shadow in points. Default 0.5.

edge_label_shadow_alpha

Transparency for shadow (0-1). Default 0.5.

edge_style

Line type(s): 1=solid, 2=dashed, 3=dotted, etc.

curvature

Edge curvature. 0 for straight, positive/negative for curves.

curve_scale

Logical: auto-curve reciprocal edges?

curve_shape

Spline tension (-1 to 1). Default 0.

curve_pivot

Position along edge for curve control point (0-1).

curves

Curve mode: TRUE (default) = single edges straight, reciprocal edges curve as ellipse (two opposing curves); FALSE = all straight; "force" = all curved.

arrow_size

Arrow head size.

arrow_angle

Arrow head angle in radians. Default pi/6 (30 degrees).

show_arrows

Logical or vector: show arrows on directed edges?

bidirectional

Logical or vector: show arrows at both ends?

loop_rotation

Angle(s) in radians for self-loop direction.

edge_start_style

Style for the start segment of edges: "solid" (default), "dashed", or "dotted". Use dashed/dotted to indicate edge direction (source node).

edge_start_length

Fraction of edge length for the styled start segment (0-0.5). Default 0.15 (15% of edge). Only applies when edge_start_style is not "solid".

edge_start_dot_density

Pattern for dotted start segments. A two-character string where the first digit is dot length and second is gap length (in line width units). Default "12" (1 unit dot, 2 units gap). Use "11" for tighter dots, "13" for more spacing. Only applies when edge_start_style = "dotted".

edge_ci

Numeric vector of CI widths (0-1 scale). Larger values = more uncertainty.

edge_ci_scale

Width multiplier for underlay thickness. Default 2.

edge_ci_alpha

Transparency for underlay (0-1). Default 0.15.

edge_ci_color

Underlay color. NA (default) uses main edge color.

edge_ci_style

Line type for underlay: 1=solid, 2=dashed, 3=dotted. Default 2.

edge_ci_arrows

Logical: show arrows on underlay? Default FALSE.

edge_label_style

Preset style: "none", "estimate", "full", "range", "stars".

edge_label_template

Template with placeholders: {est}, {range}, {low}, {up}, {p}, {stars}. Overrides edge_label_style if provided.

edge_label_digits

Decimal places for estimates. Default 2.

edge_label_oneline

Logical: single line format? Default TRUE.

edge_label_ci_format

CI format: "bracket" for ⁠[low, up]⁠ or "dash" for low-up.

edge_ci_lower

Numeric vector of lower CI bounds for labels.

edge_ci_upper

Numeric vector of upper CI bounds for labels.

edge_label_p

Numeric vector of p-values for edges.

edge_label_p_digits

Decimal places for p-values. Default 3.

edge_label_p_prefix

Prefix for p-values. Default "p=".

edge_label_stars

Stars for labels: character vector, TRUE (compute from p), or numeric (treated as p-values).

weight_digits

Number of decimal places to round edge weights to before plotting. Edges that round to zero are automatically removed. Default 2. Set NULL to disable rounding.

threshold

Minimum absolute weight to display.

minimum

Alias for threshold (qgraph compatibility). Uses max of threshold and minimum.

maximum

Maximum weight for scaling. NULL for auto.

edge_positive_color

Color for positive weights.

positive_color

Deprecated. Use edge_positive_color instead.

edge_negative_color

Color for negative weights.

negative_color

Deprecated. Use edge_negative_color instead.

edge_duplicates

How to handle duplicate edges in undirected networks. NULL (default) = stop with error listing duplicates. Options: "sum", "mean", "first", "max", "min", or a custom aggregation function.

title

Plot title.

title_size

Title font size.

margins

Margins as c(bottom, left, top, right).

background

Background color.

rescale

Logical: rescale layout to -1 to 1 range?

layout_scale

Scale factor for layout. >1 expands (spreads nodes apart), <1 contracts (brings nodes closer). Use "auto" to automatically scale based on node count (compact for small networks, expanded for large). Default 1.

layout_margin

Margin around the layout as fraction of range. Default 0.15. Set to 0 for no extra margin (tighter fit). Affects white space around nodes.

aspect

Logical: maintain aspect ratio?

use_pch

Logical: use points() for simple circles (faster). Default FALSE.

usePCH

Deprecated. Use use_pch instead.

scaling

Scaling mode: "default" for qgraph-matched scaling where node_size=6 looks similar to qgraph vsize=6, or "legacy" to preserve pre-v2.0 behavior.

legend

Logical: show legend?

legend_position

Position: "topright", "topleft", "bottomright", "bottomleft".

legend_size

Legend text size.

legend_edge_colors

Logical: show positive/negative edge colors in legend?

legend_node_sizes

Logical: show node size scale in legend?

groups

Group assignments for node coloring/legend.

node_names

Alternative names for legend (separate from labels).

filetype

Output format: "default" (screen), "png", "pdf", "svg", "jpeg", "tiff".

filename

Output filename (without extension).

width

Output width in inches.

height

Output height in inches.

res

Resolution in DPI for raster outputs (PNG, JPEG, TIFF). Default 600.

...

Additional arguments passed to layout functions.

Details

Edge Curve Behavior

Edge curving is controlled by three parameters that interact:

curves

Mode for automatic curving. FALSE = all straight, TRUE (default) = curve only reciprocal edge pairs as an ellipse, "force" = curve all edges inward toward network center.

curvature

Manual curvature amount (0-1 typical). Sets the magnitude of curves. Default 0 uses automatic 0.175 for curved edges. Positive values curve edges; the direction is automatically determined.

curve_scale

Not currently used; reserved for future scaling.

For reciprocal edges (A->B and B->A both exist), the edges curve in opposite directions to form a visual ellipse, making bidirectional relationships clear.

Weight Scaling Modes (edge_scale_mode)

Controls how edge weights are mapped to visual widths:

linear (default)

Width proportional to weight. Best when weights are similar in magnitude.

log

Logarithmic scaling. Best when weights span multiple orders of magnitude (e.g., 0.01 to 100).

sqrt

Square root scaling. Moderate compression, good for moderately skewed distributions.

rank

Rank-based scaling. Ignores actual values; uses relative ordering. All edges get equal visual spacing regardless of weight distribution.

Donut vs Pie vs Double Donut

Three ways to show additional data on nodes:

Donut (donut_fill)

Single ring showing a proportion (0-1). Ideal for completion rates, probabilities, or any single metric per node. Use donut_color for fill color and donut_bg_color for unfilled portion.

Pie (pie_values)

Multiple colored segments showing category breakdown. Ideal for composition data. Values are normalized to sum to 1. Use pie_colors for segment colors.

Double Donut (donut2_values)

Two concentric rings for comparing two metrics per node. Outer ring uses donut_fill/donut_color, inner ring uses donut2_values/donut2_colors.

CI Underlay System

Confidence interval underlays draw a wider, semi-transparent edge behind the main edge to visualize uncertainty:

edge_ci

Vector of CI widths (0-1 scale). Larger = more uncertainty.

edge_ci_scale

Multiplier for underlay width relative to main edge. Default 2 means underlay is twice as wide as main edge at CI=1.

edge_ci_alpha

Transparency of underlay (0-1). Default 0.15.

edge_ci_style

Line type: 1=solid, 2=dashed (default), 3=dotted.

Edge Label Templates

For statistical output, use templates to format complex labels:

edge_label_template

Template string with placeholders: {est} for estimate/weight, {low}/{up} for CI bounds, {range} for formatted range, {p} for p-value, {stars} for significance stars.

edge_label_style

Preset styles: "estimate" (weight only), "full" (estimate + CI), "range" (CI only), "stars" (significance).

Value

Invisibly returns the cograph_network object.

See Also

soplot for grid graphics rendering (alternative engine), cograph for creating network objects, sn_nodes for node customization, sn_edges for edge customization, sn_layout for layout algorithms, sn_theme for visual themes, from_qgraph and from_tna for converting external objects

Examples

# Basic network from adjacency matrix
adj <- matrix(c(0, 1, 1, 0,
                0, 0, 1, 1,
                0, 0, 0, 1,
                0, 0, 0, 0), 4, 4, byrow = TRUE)
splot(adj)

# With curved edges
splot(adj, curvature = 0.2)

# Weighted network with colors
w_adj <- matrix(c(0, 0.5, -0.3, 0,
                  0.8, 0, 0.4, -0.2,
                  0, 0, 0, 0.6,
                  0, 0, 0, 0), 4, 4, byrow = TRUE)
splot(w_adj, edge_positive_color = "darkgreen", edge_negative_color = "red")

# Pie chart nodes
splot(adj, pie_values = list(c(1,2,3), c(2,2), c(1,1,1,1), c(3,1)))

# Circle layout with labels
splot(adj, layout = "circle", labels = c("A", "B", "C", "D"))


Base R Arrow Drawing

Description

Arrow head drawing functions for splot() edges.


Base R Edge Rendering

Description

Edge drawing functions for splot() using base R graphics.


Base R Graphics Geometry Utilities

Description

Coordinate transformation and geometry functions for splot().


Edge Label Template Formatting

Description

Functions for formatting edge labels using templates with placeholders.


Base R Node Rendering

Description

Node drawing functions for splot() using base R graphics.


splot Parameter Vectorization Helpers

Description

Functions for resolving and vectorizing splot() parameters.


Base R Polygon Shape Definitions

Description

Vertex generation functions for polygon-based node shapes.


Calculate Angle Between Two Points

Description

Calculate Angle Between Two Points

Usage

splot_angle(x1, y1, x2, y2)

Arguments

x1, y1

Start point.

x2, y2

End point.

Value

Angle in radians.


Calculate Distance Between Two Points

Description

Calculate Distance Between Two Points

Usage

splot_distance(x1, y1, x2, y2)

Arguments

x1, y1

First point.

x2, y2

Second point.

Value

Euclidean distance.


Generate Square Vertices

Description

Generate Square Vertices

Usage

square_vertices(x, y, r)

Arguments

x

Center x coordinate.

y

Center y coordinate.

r

Half-width (vertex distance from center).

Value

List with x, y vectors of vertices.


Generate Star Vertices

Description

Generate Star Vertices

Usage

star_vertices(x, y, r, n_points = 5, inner_ratio = 0.4)

Arguments

x

Center x coordinate.

y

Center y coordinate.

r

Outer radius.

n_points

Number of star points.

inner_ratio

Ratio of inner to outer radius.

Value

List with x, y vectors of vertices.


Summary of cograph_network Object

Description

Summary of cograph_network Object

Usage

## S3 method for class 'cograph_network'
summary(object, ...)

Arguments

object

A cograph_network object.

...

Ignored.

Value

A list with network summary information (invisibly).


Classic Theme

Description

Traditional network visualization style with blue nodes and gray edges.

Usage

theme_cograph_classic()

Value

A CographTheme object.

Examples

theme <- theme_cograph_classic()

Colorblind-friendly Theme

Description

Theme using colors distinguishable by people with color vision deficiency.

Usage

theme_cograph_colorblind()

Value

A CographTheme object.

Examples

theme <- theme_cograph_colorblind()

Dark Theme

Description

Dark background theme for presentations.

Usage

theme_cograph_dark()

Value

A CographTheme object.

Examples

theme <- theme_cograph_dark()

Grayscale Theme

Description

Black and white theme suitable for print.

Usage

theme_cograph_gray()

Value

A CographTheme object.

Examples

theme <- theme_cograph_gray()

Minimal Theme

Description

Clean, minimal style with thin borders.

Usage

theme_cograph_minimal()

Value

A CographTheme object.

Examples

theme <- theme_cograph_minimal()

Nature Theme

Description

Earth tones theme inspired by nature.

Usage

theme_cograph_nature()

Value

A CographTheme object.

Examples

theme <- theme_cograph_nature()

Viridis Theme

Description

Theme using viridis color palette.

Usage

theme_cograph_viridis()

Value

A CographTheme object.

Examples

theme <- theme_cograph_viridis()

Built-in Themes

Description

Pre-defined themes for network visualization.


Theme Registry Functions

Description

Functions for registering built-in themes.


Generate TNA-style Color Palette for Nodes

Description

Internal function that generates appropriate qualitative colors based on the number of states, following TNA's color palette logic.

Usage

tna_color_palette(n_states)

Arguments

n_states

Number of states (nodes) in the network.

Value

Character vector of colors.


Generate Triangle Vertices

Description

Generate Triangle Vertices

Usage

triangle_vertices(x, y, r)

Arguments

x

Center x coordinate.

y

Center y coordinate.

r

Radius (vertex distance from center).

Value

List with x, y vectors of vertices.


Unregister SVG Shape

Description

Remove a custom SVG shape from the registry.

Usage

unregister_svg_shape(name)

Arguments

name

Shape name to remove.

Value

Invisible TRUE if removed, FALSE if not found.

Examples

# Attempt to unregister a non-existent shape (returns FALSE)
unregister_svg_shape("nonexistent")

Convert User Coordinates to Inches (X-axis)

Description

Convert User Coordinates to Inches (X-axis)

Usage

usr_to_in_x(x)

Arguments

x

Value in user coordinates.

Value

Value in inches.


Convert User Coordinates to Inches (Y-axis)

Description

Convert User Coordinates to Inches (Y-axis)

Usage

usr_to_in_y(y)

Arguments

y

Value in user coordinates.

Value

Value in inches.


Color Utilities

Description

Utility functions for color manipulation.


Deprecation Utilities

Description

Functions for handling deprecated parameters with backwards compatibility.


Geometry Utilities

Description

Utility functions for geometric calculations.


Input Validation Utilities

Description

Utility functions for validating inputs.


Validate Choice

Description

Validate Choice

Usage

validate_choice(x, choices, arg_name = "value")

Arguments

x

Value to validate.

choices

Allowed values.

arg_name

Argument name for error messages.


Validate Color

Description

Validate Color

Usage

validate_color(x, arg_name = "color")

Arguments

x

Color to validate.

arg_name

Argument name for error messages.


Validate Length Match

Description

Validate Length Match

Usage

validate_length(x, expected_length, arg_name = "value", allow_single = TRUE)

Arguments

x

Vector to validate.

expected_length

Expected length.

arg_name

Argument name for error messages.

allow_single

Allow single value (will be recycled).


Validate Network Object

Description

Validate Network Object

Usage

validate_network(x, arg_name = "network")

Arguments

x

Object to validate.

arg_name

Argument name for error messages.


Validate Numeric Range

Description

Validate Numeric Range

Usage

validate_range(x, min = -Inf, max = Inf, arg_name = "value")

Arguments

x

Value to validate.

min

Minimum allowed value.

max

Maximum allowed value.

arg_name

Argument name for error messages.


Package Load and Unload Functions

Description

Functions called when the package is loaded or unloaded.