| Title: | Automatic Plotting and Theming of Many Graphs |
| Version: | 1.2.1 |
| Description: | Visual exploration and presentation of networks should not be difficult. This package includes functions for plotting networks and network-related metrics with sensible and pretty defaults. It includes 'ggplot2'-based plot methods for many popular network package classes. It also includes some novel layout algorithms, and options for straightforward, consistent themes. |
| URL: | https://stocnet.github.io/autograph/ |
| BugReports: | https://github.com/stocnet/autograph/issues |
| License: | MIT + file LICENSE |
| Language: | en-GB |
| Encoding: | UTF-8 |
| LazyData: | true |
| Depends: | R (≥ 4.1.0), manynet (≥ 2.2.3) |
| Imports: | dplyr (≥ 1.1.0), ggraph (≥ 2.2.0), ggplot2 (≥ 4.0.0), graphlayouts (≥ 1.1.0), igraph, patchwork |
| Suggests: | gganimate, ggforce (≥ 0.5.0), gifski, methods, migraph, netrics (≥ 0.4.0), systemfonts, testthat (≥ 3.0.0) |
| Enhances: | ergm, goldfish, RSiena |
| Config/Needs/build: | roxygen2, devtools |
| Config/Needs/check: | covr, lintr, spelling |
| Config/Needs/website: | pkgdown |
| Config/testthat/parallel: | true |
| Config/testthat/edition: | 3 |
| Config/roxygen2/version: | 8.1.0 |
| NeedsCompilation: | no |
| Packaged: | 2026-08-26 15:58:40 UTC; hollway |
| Author: | James Hollway |
| Maintainer: | James Hollway <james.hollway@graduateinstitute.ch> |
| Repository: | CRAN |
| Date/Publication: | 2026-08-26 16:40:02 UTC |
autograph: Automatic Plotting of Many Graphs
Description
Visual exploration and presentation of networks should not be difficult. This package includes functions for plotting networks and network-related metrics with sensible and pretty defaults. It includes 'ggplot2'-based plot methods for many popular network package classes. It also includes some novel layout algorithms, and options for straightforward, consistent themes.
Details
For more details, please consult the README and work through the tutorial. The tutorial is available in the package documentation and on the package website.
Author(s)
James Hollway
See Also
Useful links:
Consistent palette calls
Description
These functions assist in calling particular parts of a theme's palette.
For example, ag_base() will return the current theme's base or background
color, and ag_highlight() will return the color used in that theme to
highlight one or more nodes, lines, or such.
ag_ink() returns the darker colour that theme writes with:
axis text, reference lines, and other chrome.
ag_missing() returns the neutral that theme sets aside for data that
should recede: missing values, isolates counted out of a drawing,
and any "other" remainder left when small categories are grouped down.
Keeping one colour for all three means a reader learns it once.
Keeping the two apart lets the base be light enough to stand away from
the highlight while the ink stays dark enough to read.
Where the ground changes under a theme – the "print" medium forces
white, whatever the theme prefers – ag_ink() falls back to black or
white rather than return an ink that cannot be read on it.
See check_contrast() and stocnet_medium().
Using palettes that are high contrast, aesthetically pleasing, and institutionally or thematically consistent is not without its challenges.
Usage
ag_base()
ag_ink()
ag_missing()
ag_highlight()
ag_positive()
ag_negative()
ag_qualitative(number)
ag_sequential(number)
ag_divergent(number)
ag_font()
Arguments
number |
Integer of how many category colours to return. |
Value
One or more hexcodes as strings.
Colour blindness
The default palettes are designed to be colour-blind friendly. There are different types of colour-blindness. The most common type, red-green colour-blindness, finds it difficult to distinguish between the red and green hues used in the rainbow palette, for instance. Fortunately there are a range of palettes that function fairly well for those who are color-blind. These include the viridis palette, and the ColorBrewer palettes (included in the RColorBrewer package).
An institutional palette is not ours to change, but its order is.
Each theme's categorical palette is therefore reordered when the theme is
set, so that the first colours a plot draws on are those that stay
distinct under each type of colour blindness, and ag_qualitative()
takes those colours in order rather than interpolating between them.
Divergent palettes pair a warm pole with a cool one for the same reason.
Use check_separation() to check how your own colours fare,
and simulate_colorblind() to see them as a colour-blind viewer would.
Two further questions are worth asking of a palette.
Whether its text can be read on what it sits on is a matter of contrast
rather than of hue, and check_contrast() scores it against the
thresholds of WCAG 2.1.
Whether it survives print is a matter of lightness alone, since a
greyscale device keeps the luminance of a colour and discards the rest;
simulate_colorblind(type = "grey") shows that view, and
check_separation() reports the greyscale distances beside its own score.
Most institutional palettes separate by hue and so collapse in greyscale.
Where a figure has to print in black and white, use the "bw" theme, or
add a second channel such as node_shape.
The "rainbow" theme is the exception, and is left in its own order.
Its point is fidelity to the spectrum of an observed rainbow,
which reordering would destroy,
so ag_qualitative() samples across its whole length instead.
A spectrum is not a colour-blind safe scheme:
its reds and greens are exactly the pair that red-green colour blindness
cannot separate.
Choose it where the order of the categories is itself meaningful,
and check the result with check_separation();
for categories with no order, another theme serves more readers.
Examples
# Single colours from the currently active theme
ag_base()
ag_ink()
ag_highlight()
ag_missing()
ag_positive()
ag_negative()
# Palettes of a requested length
ag_qualitative(3)
ag_sequential(5)
ag_divergent(5)
# The accessors follow whichever theme is set
ag_font()
Checking how well a layout draws its ties
Description
These functions score a drawing rather than the network it draws, so that a layout can be compared with another on the same network.
check_span() reports how many rows of nodes each tie crosses.
A layered layout should send most ties to the next row down,
and a long tie is one that skips rows to get where it is going.
check_offset() reports how far each tie travels sideways,
as a share of the width of the whole drawing.
A tie that drops straight down scores zero.
check_stress() reports how far the distances drawn
depart from the distances through the network.
A layout that draws two nodes twice as far apart as two others
should be drawing a path twice as long.
Usage
check_span(x)
check_offset(x)
check_stress(x)
Arguments
x |
A plot, as |
Details
check_span() and check_offset() answer different questions,
and a layered layout needs both answered.
check_span() asks whether the rows were well chosen,
and check_offset() asks whether the nodes were well placed within them.
The "layered" layout minimises each in turn, and its ranks and
alignment arguments choose how.
Which axis holds the rows is read from the plot,
as the axis on which the nodes take fewer distinct positions.
This is the y axis for "layered" and the x axis for "lineage",
so the same score can be compared across the two.
For a layout with no rows at all, such as "stress",
check_span() reports the distance in that axis' ranks,
which is not meaningful; the function is for layered layouts.
check_stress() applies to any layout, since every layout draws its
nodes some distance apart, and the score is the share of the path
distances that the drawn distances get wrong.
It is Kruskal's stress-1, so 0 is a perfect drawing,
and Kruskal read 20% as poor, 10% as fair, 5% as good,
and 2.5% as excellent.
Those figures were set for psychometric data rather than for networks,
which are harder: most pairs of nodes in a small-world network sit
two or three steps apart, and a plane holds few such distances at once,
so a score near 30% is ordinary and one near 5% is rare.
A layout that never set out to draw path distances,
such as "layered", "circle" or "configuration",
scores poorly by design.
The score belongs to the drawing rather than to the network,
which is what separates it from the share of distance variance
that graphr() reports beside it.
Draw one network two ways and the stress changes, since one drawing
holds its distances better than the other;
the share of variance does not, since two dimensions can hold
just as much of that network either way.
A network whose variance is held poorly sets a floor
that no layout gets under.
The drawn distances are scaled to the path distances before they are
compared, since a layout may place its nodes on any scale it likes,
and the ties are counted unweighted, as layout_scaling() counts them.
Where a network is disconnected, the pairs with no path between them
are left out of the score.
Value
check_span() returns one whole number for each tie,
with total and mean attributes holding the sum and the average.
check_offset() returns one number between 0 and 1 for each tie,
with a mean attribute.
check_stress() returns a single number of 0 or more,
with a scale attribute holding the factor the drawn distances were
scaled by, and a pairs attribute holding how many pairs were scored.
Source
Kruskal, Joseph B. 1964. "Multidimensional scaling by optimizing goodness of fit to a nonmetric hypothesis", Psychometrika 29(1): 1-27. doi:10.1007/BF02289565
See Also
Other mapping:
completion,
layout_concentric(),
layout_configuration(),
layout_correspondence(),
layout_layered(),
layout_levels(),
layout_matching(),
layout_scaling(),
layout_valence(),
plot_graphr,
plot_graphs,
plot_grapht
Examples
thrones <- manynet::to_uniplex(manynet::fict_thrones, "parent")
# The default graph is drawn once here, since each check reads the same plot.
drawn <- graphr(thrones)
# How long are the ties of the default layout?
attr(check_span(drawn), "total")
# How straight are they?
attr(check_offset(drawn), "mean")
# Compare with the layers igraph would have chosen:
# attr(check_span(graphr(thrones, ranks = "compact")), "total")
# Which layout draws the path distances best?
check_stress(graphr(manynet::ison_southern_women, layout = "scaling"))
check_stress(graphr(manynet::ison_southern_women, layout = "circle"))
Completing argument values as you type
Description
graphr() and its relatives take the names of node and tie variables,
layouts, and themes as strings, which means remembering what a network
holds. This offers those names to RStudio's completion system, so that
writing graphr(fict_lotr, node_color = " and pressing Tab lists the
variables fict_lotr holds, layout = " lists the layouts available,
and so on for every argument with a known set of values.
This is off until it is asked for, because it works by replacing one of RStudio's internal functions. That function is not part of a public interface, so a future version of RStudio can change it. Nothing else about completion changes: any line that is not one of these calls is passed to RStudio untouched, as is any line this cannot make sense of.
stocnet_completion(FALSE) puts RStudio's function back.
Usage
stocnet_completion(activate, persist = FALSE)
set_completion(activate, persist = FALSE)
Arguments
activate |
Logical, by default TRUE. If TRUE, completion of argument values is switched on. If FALSE, RStudio's own completions are restored. If missing, the current state is reported and nothing changes. |
persist |
Logical, by default FALSE.
If TRUE, the choice is remembered across sessions,
by writing it to the user's configuration directory
(see |
Value
Invisibly, TRUE where completion is now active and FALSE otherwise. Called for the effect it has on the IDE.
See Also
Other mapping:
check_layout,
layout_concentric(),
layout_configuration(),
layout_correspondence(),
layout_layered(),
layout_levels(),
layout_matching(),
layout_scaling(),
layout_valence(),
plot_graphr,
plot_graphs,
plot_grapht
Examples
## Not run:
# In RStudio, switch completion on for this session:
stocnet_completion()
# Then type graphr(fict_lotr, node_color = " and press Tab.
# To switch it off again:
stocnet_completion(FALSE)
## End(Not run)
How many pages a paged diagnostic figure has
Description
The page count of plot() on a per-term diagnostic, derivable without
rendering so a loop can write every page.
A method that only discovers it is on the last page once it gets there cannot be scripted, and scripting is the case this exists for: fits go to a cluster, so a figure has to be producible with nobody at a screen to press return.
Usage
count_pages(x, nrow = 2, ncol = 2)
Arguments
x |
a diagnostic object with one panel per term – as returned by
|
nrow, ncol |
panels per page, matching what will be passed to |
Value
A single integer, at least 1.
Examples
count_pages(goldfish_gof)
Layouts for snapping layouts to a grid
Description
The function uses approximate pattern matching to redistribute coarse layouts on square grid points, while preserving the topological relationships among the nodes (see Inoue et al. 2012).
Usage
depth_first_recursive_search(layout)
References
Inoue, Kentaro, Shinichi Shimozono, Hideaki Yoshida, and Hiroyuki Kurata. 2012. “Application of Approximate Pattern Matching in Two Dimensional Spaces to Grid Layout for Biochemical Network Maps” edited by J. Bourdon. PLoS ONE 7(6):e37739. doi:10.1371/journal.pone.0037739.
Concentric layout
Description
The "concentric" layout places the nodes on one or more circles, with each group of nodes on a circle of its own, and the groups ordered around those circles so that adjacent nodes are drawn close together. Where one group holds a single node, that node occupies the centre.
Usage
layout_concentric(
.data,
membership,
radius = NULL,
order.by = NULL,
circular = FALSE,
times = 1000
)
layout_tbl_graph_concentric(
.data,
membership,
radius = NULL,
order.by = NULL,
circular = FALSE,
times = 1000
)
Arguments
.data |
Some |
membership |
A node attribute or a vector to draw concentric circles. By default this is the two modes of a two-mode network. |
radius |
A vector of radii at which the concentric circles should be located. By default this is equal placement around an empty centre, unless one (the core) is a single node, in which case this node occupies the centre of the graph. |
order.by |
An attribute label indicating the (decreasing) order for the nodes around the circles. By default ordering is given by a bipartite placement that reduces the number of edge crossings. |
circular |
Should the layout be transformed into a radial
representation. Only possible for some layouts. Defaults to FALSE.
Required for |
times |
Maximum number of iterations, where appropriate.
Required for |
Value
Returns a table of nodes' x and y coordinates.
Source
Diego Diez, Andrew P. Hutchins and Diego Miranda-Saavedra. 2014. "Systematic identification of transcriptional regulatory modules from protein-protein interaction networks". Nucleic Acids Research, 42 (1) e6.
See Also
Other mapping:
check_layout,
completion,
layout_configuration(),
layout_correspondence(),
layout_layered(),
layout_levels(),
layout_matching(),
layout_scaling(),
layout_valence(),
plot_graphr,
plot_graphs,
plot_grapht
Examples
#graphr(ison_southern_women, layout = "concentric", membership = "type",
# node_color = "type", node_size = 3)
Layout algorithms based on configurational positions
Description
Configurational layouts locate nodes at symmetric coordinates to help illustrate particular configurations. Currently configurational layouts are available for 2-6 nodes. The "configuration" layout will choose the appropriate configurational layout automatically.
Usage
layout_configuration(.data, circular = TRUE, times = 1)
layout_tbl_graph_configuration(.data, circular = TRUE, times = 1)
layout_dyad(.data, circular = TRUE, times = 1)
layout_triad(.data, circular = TRUE, times = 1)
layout_tetrad(.data, circular = TRUE, times = 1)
layout_pentad(.data, circular = TRUE, times = 1)
layout_hexad(.data, circular = TRUE, times = 1)
Arguments
.data |
Some |
circular |
Should the layout be transformed into a radial
representation. Only possible for some layouts. Defaults to FALSE.
Required for |
times |
Maximum number of iterations, where appropriate.
Required for |
Value
Returns a table of nodes' x and y coordinates.
See Also
Other mapping:
check_layout,
completion,
layout_concentric(),
layout_correspondence(),
layout_layered(),
layout_levels(),
layout_matching(),
layout_scaling(),
layout_valence(),
plot_graphr,
plot_graphs,
plot_grapht
Examples
# "configuration" picks the layout matching the number of nodes
graphr(manynet::create_ring(4), layout = "configuration")
# the specific configurations are also available as functions
layout_tetrad(manynet::create_ring(4))
Correspondence layout
Description
The "correspondence" layout places nodes by correspondence analysis, so that two nodes are drawn together where they have similar ties. Where the "scaling" layout reads the paths between nodes, this one reads the profile of each node's ties, and so two nodes with no tie between them can still be drawn together if they are tied to the same others.
This is the usual way to draw a two-mode network, since correspondence analysis takes a rectangular table and places its rows and its columns in one space. Both modes are therefore drawn on one pair of axes.
Like the "scaling" layout, the coordinates can be read, and so this layout draws labelled axes at a fixed ratio. Each axis is labelled with the share of the network's inertia that the dimension holds.
Usage
layout_correspondence(
.data,
direction = c("all", "out", "in"),
double = FALSE,
circular = FALSE,
times = 1
)
layout_tbl_graph_correspondence(
.data,
direction = c("all", "out", "in"),
double = FALSE,
circular = FALSE,
times = 1
)
Arguments
.data |
Some |
direction |
Which ties to read for a directed network, as one of "all", "out", or "in". By default this is "all", which reads a tie in either direction, so that each node has one position. "out" places each node by the ties it sends, and "in" by the ties it receives. This is ignored where the network is undirected or two-mode. |
double |
Whether to split each tie into a positive and a negative part,
so that a signed network can be drawn.
By default this is |
circular |
Should the layout be transformed into a radial
representation. Only possible for some layouts. Defaults to FALSE.
Required for |
times |
Maximum number of iterations, where appropriate.
Required for |
Details
Correspondence analysis divides the ties of each node by how many ties that node has, and so places nodes by the shape of their ties rather than by how many they have. The distance drawn is the chi-square distance between two such profiles.
A two-mode network is read as its incidence matrix, one row for each node of the first mode and one column for each of the second. A one-mode network is read as its adjacency matrix instead, as is a multimodal network that has ties within its modes as well as between them, so that no tie is dropped.
Tie weights are read as they are, since correspondence analysis was built
for counts and a weight counts in the same way.
A negative weight has no such reading, which is why a signed network
needs double = TRUE. That stacks the positive network and the negative
network side by side, doubling the width of the table,
so that a node is placed by both who it is tied to positively
and who it is tied to negatively.
A pair of nodes with no tie between them counts in neither half.
Value
Returns a table of nodes' x and y coordinates.
Reading the plot
Two nodes of the same mode drawn together have similar ties.
A node drawn near the origin has a profile close to the average,
or is held poorly by the two dimensions drawn: these are not the same
thing, and graphr() names the nodes for which it is the second.
A node of one mode drawn near a node of the other mode is not necessarily tied to it. Only the distances within a mode can be read this way.
Where a network runs along one strong gradient, correspondence analysis draws it as an arch rather than as a line. This is expected of the method, and the second dimension then repeats the first rather than adding to it.
Where a network is disconnected, the first dimensions merely separate its components, and say little about the nodes within them.
Reading the inertia
The share of inertia a dimension holds is not a share of variance
explained, and does not have a fixed ceiling to be read against.
It is a share of however many dimensions the table has,
which attr(x, "fit")$scree reports in full.
Two dimensions of a table that has twelve start from a base of a sixth;
two of a table that has thirty start from a base of a fifteenth.
Compare the share drawn against that base rather than against 100%,
and note that this can reverse the ranking the raw shares suggest.
Bear in mind that an even share is a lenient base, since inertia is
never spread evenly; the broken stick model asks what the dimensions
would hold if the inertia were divided at random, and is the harder test.
Neither is a standard statistic, and neither carries a threshold,
so read them as a check on the raw share rather than as a verdict.
graphr() says so at the console where two dimensions hold no more
than a random division of the inertia would give them.
To choose a number of dimensions properly, see Lorenzo-Seva (2011).
These shares need no correction. The Benzécri correction, and Greenacre's adjusted version of it, exist because the indicator matrix that multiple correspondence analysis is run on invents dimensions that deflate every share. This layout runs simple correspondence analysis on one two-way table, which invents nothing, so the shares reported are already exact.
Source
Greenacre, Michael. 2017. Correspondence Analysis in Practice, 3rd ed. Boca Raton: Chapman and Hall. doi:10.1201/9781315369983
Lorenzo-Seva, Urbano. 2011. "Horn's parallel analysis for selecting the number of dimensions in correspondence analysis", Methodology 7(3): 96-105. doi:10.1027/1614-2241/a000027
Constantine, A.G., and John C. Gower. 1978. "Graphical representation of asymmetric matrices", Journal of the Royal Statistical Society C 27(3): 297-304. doi:10.2307/2347234
See Also
Other mapping:
check_layout,
completion,
layout_concentric(),
layout_configuration(),
layout_layered(),
layout_levels(),
layout_matching(),
layout_scaling(),
layout_valence(),
plot_graphr,
plot_graphs,
plot_grapht
Examples
graphr(manynet::ison_southern_women, layout = "correspondence")
Deprecated layout names
Description
Each of these draws what its replacement draws, after saying so. They are kept so that a call naming the older layout still draws, and will be removed.
"hierarchy" is now "layered", which is what the layout does to a two-mode network, where the two modes are two layers and neither is above the other in any hierarchy.
"alluvial" is now "lineage". The name is held for a plot of changing membership composition over time.
"multilevel" is now "levels", which
{graphlayouts}does not also use."dyad", "triad", "tetrad", "pentad" and "hexad" are now all "configuration", which already picks the one matching the number of nodes. The functions of those names are not deprecated.
Note that .deprecated_layouts() lists these, so that neither the
completions nor the functional audit offers a retired name.
Usage
layout_hierarchy(.data, ...)
layout_tbl_graph_hierarchy(.data, ...)
layout_alluvial(.data, ...)
layout_tbl_graph_alluvial(.data, ...)
layout_multilevel(.data, ...)
layout_tbl_graph_multilevel(.data, ...)
layout_tbl_graph_dyad(.data, ...)
layout_tbl_graph_triad(.data, ...)
layout_tbl_graph_tetrad(.data, ...)
layout_tbl_graph_pentad(.data, ...)
layout_tbl_graph_hexad(.data, ...)
Arguments
.data |
Some |
... |
Arguments passed on to the replacement layout. |
Value
Returns a table of nodes' x and y coordinates.
Layered layouts
Description
These algorithms assign each node to a layer, which becomes one axis,
and a position within that layer, which becomes the other.
They are recommended for use with graphr() or {ggraph},
and suit two-mode networks and directed acyclic networks.
The four layouts are one engine drawn four ways, and differ only in which axis carries the layers and in how each layer is spread out:
| Layers stacked flat | Layers standing up | |
alignment = "straight" | "layered" | "lineage" |
alignment = "rungs" | "railway" | "ladder" |
That is, the "layered" layout places the first node set along the bottom and the second node set along the top, sequenced and spaced as necessary to minimise tie overlap. The "lineage" layout is the same layout with the axes exchanged, so that successive layers run left to right rather than bottom to top. The "railway" and "ladder" layouts are "layered" and "lineage" with every layer given the same spacing, so that the nodes line up across the layers like the rails and rungs the names describe.
Usage
layout_layered(
.data,
center = NULL,
ranks = c("tight", "generation", "compact"),
alignment = c("straight", "rungs"),
circular = FALSE,
times = 1000
)
layout_tbl_graph_layered(
.data,
center = NULL,
ranks = c("tight", "generation", "compact"),
alignment = c("straight", "rungs"),
circular = FALSE,
times = 1000
)
layout_lineage(
.data,
ranks = c("tight", "generation", "compact"),
alignment = c("straight", "rungs"),
circular = FALSE,
times = 1000,
rank = NULL
)
layout_tbl_graph_lineage(
.data,
ranks = c("tight", "generation", "compact"),
alignment = c("straight", "rungs"),
circular = FALSE,
times = 1000,
rank = NULL
)
layout_railway(
.data,
ranks = c("tight", "generation", "compact"),
circular = FALSE,
times = 1000
)
layout_tbl_graph_railway(
.data,
ranks = c("tight", "generation", "compact"),
circular = FALSE,
times = 1000
)
layout_ladder(
.data,
ranks = c("tight", "generation", "compact"),
circular = FALSE,
times = 1000
)
layout_tbl_graph_ladder(
.data,
ranks = c("tight", "generation", "compact"),
circular = FALSE,
times = 1000
)
Arguments
.data |
Some |
center |
Further split a "layered" layout by declaring the "center" argument as the "events", "actors", or by declaring a node name. Defaults to NULL. |
ranks |
How the layers are assigned:
"tight" (the default) chooses the layers that make the total tie length
as short as possible, while still pointing every tie down at least one
layer;
"generation" ranks each node by its distance from a root, so that a layer
is a generation, at the cost of some longer ties;
"compact" asks A node attribute can be given here instead, either as the name of a numeric node attribute or as a numeric vector as long as the network has nodes. Then the layers are those values, and nodes are placed along that axis in proportion to them rather than at even steps, so that a network of dated nodes is drawn as a timeline. The values run in the same direction as the layers the engine works out: down the page in a "layered" or "railway" layout, and left to right in a "lineage" or "ladder" layout, so that the smallest value comes first. |
alignment |
How each layer is spread out: "straight" (the default) draws the ties as close to straight as the ordering allows, which groups the nodes that belong together; "rungs" gives every layer the same integer spacing, so that the nodes line up across the layers. |
circular |
Should the layout be transformed into a radial
representation. Only possible for some layouts. Defaults to FALSE.
Required for |
times |
Maximum number of iterations, where appropriate.
Required for |
rank |
Deprecated. Use |
Value
Returns a table of nodes' x and y coordinates.
See Also
Other mapping:
check_layout,
completion,
layout_concentric(),
layout_configuration(),
layout_correspondence(),
layout_levels(),
layout_matching(),
layout_scaling(),
layout_valence(),
plot_graphr,
plot_graphs,
plot_grapht
Examples
#graphr(ison_southern_women, layout = "layered", center = "events",
# node_color = "type", node_size = 3)
#graphr(ison_southern_women, layout = "lineage")
# ison_adolescents |>
# mutate(year = rep(c(1985, 1990, 1995, 2000), times = 2)) |>
# graphr(layout = "lineage", ranks = "year")
Levels layout
Description
The "levels" layout draws each level of a multilevel network as a plane of its own, projected at an angle, with the ties within each level drawn on its plane and the ties between levels drawn between them.
Note that {graphlayouts} offers a layout of the same idea under the
name "multilevel". This one is named for its level argument.
Usage
layout_levels(
.data,
level,
method = c("all", "separate", "fix1", "fix2"),
circular = FALSE,
times = 1,
alpha = 25,
beta = 45,
FUN1 = graphlayouts::layout_with_stress,
FUN2 = graphlayouts::layout_with_stress
)
layout_tbl_graph_levels(
.data,
level,
method = c("all", "separate", "fix1", "fix2"),
circular = FALSE,
times = 1,
alpha = 25,
beta = 45,
FUN1 = graphlayouts::layout_with_stress,
FUN2 = graphlayouts::layout_with_stress
)
Arguments
.data |
Some |
level |
A node attribute or a vector to hierarchically order levels.
By default the levels are those already recorded in a "lvl" node attribute,
as |
method |
How the levels should be laid out: "all" (the default) lays every level out at once, "separate" lays each level out independently, and "fix1" and "fix2" lay out the first or second level respectively and derive the other from it. Note that all but "all" require ties within the levels they lay out. |
circular |
Should the layout be transformed into a radial
representation. Only possible for some layouts. Defaults to FALSE.
Required for |
times |
Maximum number of iterations, where appropriate.
Required for |
alpha, beta |
The angles, in degrees, at which the levels are projected onto the plane. |
FUN1, FUN2 |
The layout functions used for the first and second levels
respectively by the "separate", "fix1" and "fix2" methods.
By default both are |
Value
Returns a table of nodes' x and y coordinates.
See Also
Other mapping:
check_layout,
completion,
layout_concentric(),
layout_configuration(),
layout_correspondence(),
layout_layered(),
layout_matching(),
layout_scaling(),
layout_valence(),
plot_graphr,
plot_graphs,
plot_grapht
Examples
# fict_marvel interlocks a one-mode layer of ties among its characters
# with a two-mode layer of their affiliations, so it is laid out this way
# by default; the levels need not be named.
graphr(manynet::fict_marvel, labels = FALSE)
Matching layout
Description
This layout works to position nodes opposite their matching nodes.
See manynet::to_matching() for more details on the matching procedure.
Usage
layout_matching(.data, center = NULL, circular = FALSE, times = 1)
layout_tbl_graph_matching(.data, center = NULL, circular = FALSE, times = 1)
Arguments
.data |
Some |
center |
Required for |
circular |
Should the layout be transformed into a radial
representation. Only possible for some layouts. Defaults to FALSE.
Required for |
times |
Maximum number of iterations, where appropriate.
Required for |
Value
Returns a table of nodes' x and y coordinates.
See Also
Other mapping:
check_layout,
completion,
layout_concentric(),
layout_configuration(),
layout_correspondence(),
layout_layered(),
layout_levels(),
layout_scaling(),
layout_valence(),
plot_graphr,
plot_graphs,
plot_grapht
Scaling layout
Description
The "scaling" layout places nodes by multidimensional scaling, so that the distance drawn between two nodes approximates the number of steps of the shortest path between them. Unlike a force-directed layout, then, the coordinates can be read, and so this layout draws labelled axes, at a fixed ratio so that the two axes share one scale.
Which algorithm is used depends on the size of the network.
Up to a hundred nodes, classical multidimensional scaling is used,
as igraph::layout_with_mds() offers it.
Above that, or where pivots is given,
pivot multidimensional scaling is used instead,
as graphlayouts::layout_with_pmds() offers it,
which approximates the same solution from a sample of the nodes
and is much the faster for a large network.
Note that "mds" and "pmds" remain available as layouts in their own right,
though "pmds" then requires its own pivots.
Two dimensions rarely hold every path distance of a network at once,
so graphr() captions the plot with how well this one does:
see check_stress() for how to read the score.
Usage
layout_scaling(.data, pivots = NULL, circular = FALSE, times = 1)
layout_tbl_graph_scaling(.data, pivots = NULL, circular = FALSE, times = 1)
Arguments
.data |
Some |
pivots |
The number of nodes to approximate the scaling from.
By default this is |
circular |
Should the layout be transformed into a radial
representation. Only possible for some layouts. Defaults to FALSE.
Required for |
times |
Maximum number of iterations, where appropriate.
Required for |
Details
The distances scaled are those of the unweighted network, that is, the number of ties on the shortest path between two nodes. Tie weights are ignored, since the interpretation of a drawn distance is then the same whatever the network, and since a signed network has no shortest paths to speak of.
Where a network is disconnected, there is no path between its components, and so no distance to scale. Each component is laid out and the components are then placed beside one another, and the fit is reported over the pairs of nodes that a path does connect.
Value
Returns a table of nodes' x and y coordinates.
Source
Kruskal, Joseph B. 1964. "Multidimensional scaling by optimizing goodness of fit to a nonmetric hypothesis", Psychometrika 29(1): 1-27. doi:10.1007/BF02289565
Brandes, Ulrik, and Christian Pich. 2007. "Eigensolver methods for progressive multidimensional scaling of large data", in Graph Drawing, 42-53. doi:10.1007/978-3-540-70904-6_6
See Also
Other mapping:
check_layout,
completion,
layout_concentric(),
layout_configuration(),
layout_correspondence(),
layout_layered(),
layout_levels(),
layout_matching(),
layout_valence(),
plot_graphr,
plot_graphs,
plot_grapht
Examples
graphr(manynet::ison_southern_women, layout = "scaling")
Valence layout
Description
The "valence" layout places the nodes of a signed network so that positively tied nodes are drawn together and negatively tied nodes apart.
Usage
layout_valence(
.data,
times = 500,
center = NULL,
circular = FALSE,
repulsion_coef = 1,
attraction_coef = 0.05
)
layout_tbl_graph_valence(
.data,
times = 500,
center = NULL,
circular = FALSE,
repulsion_coef = 1,
attraction_coef = 0.05
)
Arguments
.data |
Some |
times |
Maximum number of iterations, where appropriate.
Required for |
center |
Required for |
circular |
Should the layout be transformed into a radial
representation. Only possible for some layouts. Defaults to FALSE.
Required for |
repulsion_coef |
Coefficient for global repulsion force. Default is 1. |
attraction_coef |
Coefficient for edge-based attraction/repulsion force. Default is 0.05. |
Value
Returns a table of nodes' x and y coordinates.
See Also
Other mapping:
check_layout,
completion,
layout_concentric(),
layout_configuration(),
layout_correspondence(),
layout_layered(),
layout_levels(),
layout_matching(),
layout_scaling(),
plot_graphr,
plot_graphs,
plot_grapht
Examples
edges <- data.frame(
from = c("A", "B", "C", "D"),
to = c("B", "C", "D", "A"),
weight = c(2, 3, 1, 4),
sign = c(1, -1, 1, -1) # 1 = positive, -1 = negative
)
graphr(as_igraph(edges), layout="valence")
Listing the fonts available to R
Description
list_fonts() reports the font families that R can currently see,
which is what a theme's preferred fonts are matched against.
A font that is installed on the system but missing from this list is not
available to R yet;
see the Fonts section of theme_set for how to make it so.
Usage
list_fonts(pattern = NULL)
Arguments
pattern |
Optionally, a string with which to filter the font families
returned, matched without regard to case.
For example, |
Value
A vector of font family names.
See Also
Other themes:
theme_colorblind,
theme_medium,
theme_set
Examples
head(list_fonts())
Precooked results for demonstrating plotting
Description
These are all pre-cooked results objects, saved here to save time in testing and demonstrating how autograph plots look.
Usage
data(res_migraph_reg)
data(res_migraph_test)
data(res_migraph_diff)
data(res_manynet_diff)
data(siena_gof)
data(siena_influence)
data(siena_selection)
data(monan_conv)
data(monan_gof)
data(ergm_gof)
data(goldfish_outliers)
data(goldfish_changepoints)
data(goldfish_margins)
data(goldfish_gof)
data(goldfish_time)
data(goldfish_onset)
data(goldfish_fit)
Format
An object of class netlm of length 15.
An object of class network_test of length 9.
An object of class diffs_model (inherits from data.frame) with 20 rows and 11 columns.
An object of class diff_model (inherits from tbl_df, tbl, data.frame) with 4 rows and 10 columns.
An object of class sienaGOF of length 1.
An object of class influenceTable (inherits from data.frame) with 25 rows and 4 columns.
An object of class selectionTable (inherits from data.frame) with 25 rows and 4 columns.
An object of class traces.monan of length 3.
An object of class gof.stats.monan of length 2.
An object of class gof.ergm (inherits from gof) of length 30.
An object of class goldfishOutliers (inherits from tbl_df, tbl, data.frame) with 439 rows and 11 columns.
An object of class goldfishChangepoints (inherits from tbl_df, tbl, data.frame) with 115 rows and 10 columns.
An object of class goldfishMargins (inherits from tbl_df, tbl, data.frame) with 308 rows and 5 columns.
An object of class goldfishGOF (inherits from list) of length 3.
An object of class goldfishTimeTest (inherits from list) of length 3.
An object of class goldfishOnset (inherits from list) of length 3.
An object of class goldfishFit of length 31.
Plotting logical marks Plotting numeric measures
Description
These functions plot distributions for node, tie, and network measures,
as defined in the {manynet} package.
Usage
## S3 method for class 'node_measure'
plot(x, type = c("h", "d"), ...)
## S3 method for class 'tie_measure'
plot(x, type = c("h", "d"), ...)
## S3 method for class 'network_measures'
plot(x, ...)
Arguments
x |
An object of "node_measure", "tie_measure", or "network_measures" class. |
type |
For node and tie measures, whether the plot should be "h" a histogram or "d" a density plot. By default "h". |
... |
Other arguments to be passed on. |
Value
plot.node_measure() and plot.tie_measure() returns a histogram
and/or density plot of the distribution of the measure.
plot.network_measures() returns a plot of the measure traced over
time.
Examples
plot(netrics::node_by_deg(ison_karateka))
plot(netrics::tie_by_betweenness(ison_karateka))
Plotting categorical memberships
Description
This plotting method operates on "node_member" class objects from the
{manynet} package, plotting the dendrogram of their membership.
Usage
## S3 method for class 'node_member'
plot(x, ...)
## S3 method for class 'matrix'
plot(x, ..., membership = NULL)
Arguments
x |
An object of "node_member" class, for example as a result of
running |
... |
Other arguments to be passed on. |
membership |
A "node_member" membership vector. |
Value
plot.node_member() returns a dendrogram, with labels colored to
indicate the different clusters, and with the optimal cutpoint shown by a
dashed highlight line.
plot.matrix() returns a plot of an adjacency or incidency matrix,
potentially with the rows and columns reordered to illustrate an additional
membership vector.
Examples
plot(netrics::node_in_walktrap(ison_southern_women, "e"))
plot(as_matrix(ison_adolescents),
membership = netrics::node_in_walktrap(ison_adolescents, "e"))
plot(as_matrix(ison_southern_women),
membership = netrics::node_in_walktrap(ison_southern_women, "e"))
Plotting tabular motifs
Description
These functions will plot graphs of the motifs used in a vector of results of e.g. a triad census.
Usage
## S3 method for class 'node_motif'
plot(x, ...)
## S3 method for class 'network_motif'
plot(x, ...)
Arguments
x |
An object of "node_motif" class, e.g. resulting from a call to
|
... |
Other arguments to be passed on. |
Value
plot.node_motif() returns a set of graphs that illustrate the
motifs mentioned in the results from a node_motif function in {manynet}.
plot.network_motif() returns a set of graphs that illustrate the
motifs mentioned in the results from a net_motif function in {manynet}.
Plotting methods for MRQAP models
Description
These plotting methods are for results obtained by fitting an MRQAP
model.
The S3 classes are "netlm" or "netlogit", and so are compatible with the
results from either the {sna} or {migraph} packages.
Usage
## S3 method for class 'netlm'
plot(x, ...)
## S3 method for class 'netlogit'
plot(x, ...)
Arguments
x |
An object obtained by fitting an MRQAP model to some data.
For example, |
... |
Further arguments to be passed on to plot. |
Value
A plot showing the location of observed statistics compared to the distribution of statistics from permuted networks.
Examples
# Here's something I cooked up with migraph earlier:
plot(res_migraph_reg)
Plotting adequacy diagnostics
Description
These plotting methods are for diagnosing the adequacy of model specification, such as those used in goldfish. These plots are useful for identifying whether there might be significant outliers affecting the results, whether there is significant time heterogeneity, and which actors' activity the model does not reproduce.
Usage
## S3 method for class 'diagnose_outliers'
plot(x, ...)
## S3 method for class 'outliers.goldfish'
plot(x, ...)
## S3 method for class 'diagnose_changepoints'
plot(x, ...)
## S3 method for class 'changepoints.goldfish'
plot(x, ...)
## S3 method for class 'goldfishOutliers'
plot(x, ...)
## S3 method for class 'goldfishChangepoints'
plot(x, ...)
## S3 method for class 'goldfishMargins'
plot(x, ..., top = 25)
## S3 method for class 'goldfishGOF'
plot(x, ..., level = 0.95, page = NULL, nrow = 2, ncol = 2)
## S3 method for class 'goldfishTimeTest'
plot(x, ..., page = NULL, nrow = 2, ncol = 2)
## S3 method for class 'goldfishOnset'
plot(
x,
...,
view = c("both", "path", "accrual"),
tolerance_band = TRUE,
page = NULL,
nrow = 2,
ncol = 2
)
Arguments
x |
An object of class |
... |
Additional plotting parameters, currently unused. |
top |
The number of actors to draw, those furthest from the reference. |
level |
The confidence level of the reference bands, defaulting to 0.95. The band is the two-sided Kolmogorov quantile of the supremum of a Brownian bridge, which is the reference the event-clock p-value uses. |
page |
Which page to draw, for the per-term figures. |
nrow, ncol |
Panels per page when |
view |
Which panels to draw: |
tolerance_band |
Whether to draw each coefficient's stabilization
band, the |
Details
plot.diagnose_outliers(), plot.outliers.goldfish(),
plot.diagnose_changepoints() and plot.changepoints.goldfish() are
aliases for plot.goldfishOutliers() and plot.goldfishChangepoints(),
kept so that an object carrying one of the older class names plots as
before. Each reads the columns the current methods read. They will be
removed.
goldfish emits these objects plot-ready. Each is a tibble carrying the diagnostic metadata contract — which function produced it, which model and sub-model it came from, and the arguments that shape how it is read — so these methods take their series, their labels and their reference lines from the object rather than inferring them from the columns that happen to be present.
The .series column is the series the diagnostic actually analysed: the
per-interval log-likelihood by default, and the selected term's own
series when the diagnostic was called with effect =. It is NA on the
intervals that took no part, which on a rate or REM fit are the
right-censored ones.
plot.goldfishMargins() shows each actor's observed activity against what
the model expected of them. Which comparison it draws follows the scales
the fit's model class defines, which the object records: where a
compensator is defined (the exact-time sub-models) the difference
observed - expected_count is the per-actor martingale residual, read
against zero; on the multinomial sub-models, which have no exposure-time
term and so no compensator, the ratio observed / expected_probability
is a calibration ratio, read against one.
These are descriptives rather than per-actor tests: the differences are plug-in quantities and are negatively correlated across actors. Read the plot as a map screening for unmodelled actor heterogeneity.
A node set large enough to make one row per actor unreadable is the
ordinary case, so only the top actors furthest from the reference are
drawn, and the subtitle says how many were left out. Actors are ranked by
their largest deviation over the roles they appear in, so an actor kept
for one margin keeps the other beside it. Pass top = Inf for all of
them.
plot.goldfishGOF() draws each effect's standardized cumulative score
process against the Brownian-bridge bands its p-value was read from. At
the maximum the per-event scores sum to zero, so every path starts and
ends at zero; under a correctly specified model it is a bridge, and a path
that wanders outside the bands is an effect whose contribution is
concentrated somewhere in the sequence.
The x axis is the object's own process-time axis, taken from its u
column and labelled by the clock it records. This is not a
presentational detail: the bands are valid on whichever clock produced the
process, and re-deriving an event-index axis here would draw the path on
one clock and the reference on another. On the information clock the
spacing of the steps is itself the diagnostic — a path that crosses most
of the axis in a few steps is an effect whose information arrives late.
plot.goldfishTimeTest() draws the scaled Schoenfeld residuals of each
tested effect against time, with a smooth and the fitted estimate as the
reference. A residual scatter is centred on the coefficient the model
estimated; a smooth that drifts away from that line over the sequence is
the coefficient failing to be constant, which is what the test's p-value
states formally.
Under method = "periods" the intervals are coloured by their period, so
the regimes the test compared are visible against the same scatter.
plot.goldfishOnset() composes two panels: each coefficient's
leave-the-first-m-events-out path, and the share of the model's
information those events delivered.
Both panels are windowed on the excursion rather than the sequence, because the full range is mostly bridge tail — the path returns to the estimate by construction, so drawing all of it squashes the part being read into a few percent of the axis. Each coefficient gets its own window and its own x scale, since coefficients settle at very different points and a window shared across facets re-creates the squashing it exists to prevent. A coefficient whose path never left its band takes the full range, there being no excursion to window on.
The accrual panel is drawn full-range with the onset window shaded, and
carries the proportional diagonal y = x / n. Without the diagonal a
monotone curve from 0 to 1 says nothing: the signal is the departure
from proportional, which is what makes an opening segment that carries
little information visible.
Coefficients held fixed through offset() are not drawn. Their path is a
flat line at the imposed value by construction.
Value
A ggplot object.
Examples
plot(goldfish_outliers)
plot(goldfish_changepoints)
plot(goldfish_margins)
plot(goldfish_gof)
plot(goldfish_time)
plot(goldfish_onset)
Plotting diffusion models
Description
Plotting diffusion models
Usage
## S3 method for class 'diff_model'
plot(x, ..., all_steps = TRUE)
## S3 method for class 'diffs_model'
plot(x, ...)
## S3 method for class 'learn_model'
plot(x, ...)
Arguments
x |
A "diff_model" of "diffs_model" class of object.
E.g. as a result from |
... |
Other arguments to be passed. |
all_steps |
Whether all steps should be plotted or just those where there is change in the distributions. |
Value
plot.diff_model() returns a bar chart of the number of new
infected nodes at each time point, as well as an overlay line plot of the
total of infected
Examples
plot(res_manynet_diff)
plot(res_migraph_diff)
plot(play_learning(ison_networkers, beliefs = runif(net_nodes(ison_networkers))))
Plotting methods for CUG and QAP tests
Description
These plotting methods are for results obtained by testing some statistic against those produced in a reference distribution of conditional uniform graphs or as a quadratic assignment procedure. The S3 class is "network_test".
Usage
## S3 method for class 'network_test'
plot(x, ..., threshold = 0.95, tails = c("two", "one"))
Arguments
x |
An object obtained from a conditional uniform graph or
quadratic assignment procedure test.
For example, |
... |
Other arguments to be passed on. |
threshold |
The empirical threshold to shade in the plot. |
tails |
By default "two" indicating a two-tailed test, but "one" for a one-tailed test is also available. |
Value
A distribution of the simulated or permuted statistics, with 2.5% shaded at each end, and a line highlighting where the observed statistic lies on this distribution.
Examples
# Here's something I cooked up with migraph earlier:
plot(res_migraph_test)
Plotting a goldfish model fit at a glance
Description
One call, four diagnostic panels: whether any interval is badly fitted, whether any coefficient drifts, whether each effect's contribution is spread over the sequence, and whether the waiting times are what the model says they are.
Usage
## S3 method for class 'result.goldfish'
plot(x, ..., effects = 4)
## S3 method for class 'goldfishFit'
plot(x, ..., effects = 4)
Arguments
x |
A fitted model of class |
... |
Additional plotting parameters, currently unused. |
effects |
The number of effects to draw in the Schoenfeld panel. |
Details
plot.result.goldfish() is an alias for plot.goldfishFit(), kept so that
a fit from a goldfish that still stamps the old class name plots as before.
It will be removed.
Everything is drawn from what the fit already stores — no evaluation pass and no preprocessed statistics — so the figure costs a plot and not a re-fit. The consequence is that a panel needing a primitive the fit did not store is left out rather than erroring: which panels appear is itself a readout of what was requested at estimation.
- deviance
the per-interval log-likelihood with outlying intervals marked. Needs the
"loglik"primitive.- scaled Schoenfeld
a smooth per effect against the fitted estimate, flat under a constant coefficient. Needs
"scores"on a multinomial sub-model, and"conditional_scores"on an exact-time one, where the score carries an exposure term the Schoenfeld residual does not.- cumulative score
each effect's standardized process against its Brownian-bridge band. Needs
"scores".- waiting times
the Cox-Snell residuals against the unit exponential they follow under the model. Exact-time sub-models only: an ordinal likelihood conditions the timing away, so there is no waiting time to check.
The Schoenfeld panel is capped at the effects most worth looking at,
ranked by their cumulative-score statistic, since a model with a dozen
terms makes a facet grid unreadable at overview size.
Value
A patchwork composition of the available panels.
Examples
plot(goldfish_fit)
Plotting convergence diagnostics
Description
These plotting methods are for diagnosing the convergence of simulation-based estimation procedures, such as those used in MoNAn and ergm. These plots are useful for identifying whether the estimation procedure has adequately explored the state space and converged to a stable distribution.
Usage
## S3 method for class 'ag_conv'
plot(x, ...)
## S3 method for class 'traces.monan'
plot(x, ...)
## S3 method for class 'ergm'
plot(x, ...)
load_ergm_res()
Arguments
x |
An object of class "traces.monan". |
... |
Additional plotting parameters, currently unused. |
Value
The function shows a line plot tracing the statistics obtained at each simulation step, as well as a density plot showing the distribution of the statistics over the entire simulation.
See Also
Other MoNAn:
plot_gof
Other ergm:
plot_gof
Examples
plot(monan_conv)
ergm_res <- load_ergm_res()
plot(ergm_res)
Plotting goodness-of-fit results
Description
These plot methods plot goodness of fit objects created using
RSiena::sienaGOF(), MoNAn::monanGOF(), or the 'ergm' package's gof() function.
Internally, the GOF object is translated into a common class (ag_gof),
which has its own plot method to ensure a consistent look and feel.
It is not expected that users will create ag_gof class objects themselves.
The plot shows a violin plot of the distribution of statistics from the
simulations, with a boxplot inside the violin to show the interquartile range,
and dashed lines connecting the 5th and 95th percentiles.
The boxplot also shows outliers as crosses.
The observed statistics are shown as points and connected by a line.
The observed statistics are also labelled with their value.
If a p-value is available (as in the case of RSiena::sienaGOF()),
it is shown beneath the x-axis.
Usage
## S3 method for class 'ag_gof'
plot(x, ...)
## S3 method for class 'gof.stats.monan'
plot(x, cumulative = FALSE, ...)
## S3 method for class 'sienaGOF'
plot(x, cumulative = FALSE, ...)
## S3 method for class 'gof.ergm'
plot(
x,
cumulative = FALSE,
statistic = c("degree", "odegree", "idegree", "b1degree", "b2degree", "espartners",
"dspartners", "distance"),
...
)
Arguments
x |
An object of class "sienaGOF", "gof.stats.monan", or "gof.ergm". |
... |
Other parameters to be passed to the plotting function,
for example |
cumulative |
Logical, indicating whether the statistics should be
plotted cumulatively (default FALSE).
This is typically treated in |
statistic |
Character, indicating which statistic to plot.
Since 'ergm' package GOFs include goodness of fit on multiple statistics,
the user must specify which statistic to plot.
Options are |
Details
Since these plots methods are in {autograph},
the plots are automatically themed according to the current theme
set using stocnet_theme().
The function uses the highlight colour defined in the current theme
to highlight the observed statistics.
The function also uses the base colour defined in the current theme
to draw the violin and box plots.
It is however completely customisable.
While a title is automatically generated so that the graph is informative,
this can be customised by specifying the main argument in the plotting function,
or added after the fact using {ggplot2} functions such as
ggtitle() or labs().
The user can choose whether to plot the statistics cumulatively or not.
This is typically handled within RSiena::sienaGOF(),
but for MoNAn::monanGOF() and the 'ergm' package's gof() function
the cumulative option is handled here.
The default is to plot the non-cumulative statistics.
This is because the non-cumulative statistics are often more interpretable,
and the cumulative statistics can be obtained by setting cumulative = TRUE.
The function also checks whether any of the statistics have zero variance across the simulations, and if so, these statistics are not plotted, with a message to the user indicating which statistics were omitted.
Note that these methods overwrite any plot methods for these classes
that may be provided by the original packages.
You may receive such a warning in the console when loading the package.
Please load {autograph} after these other packages to ensure the plotting
methods included in this package are used,
or specify the package when calling the plotting method directly,
e.g., autograph:::plot.sienaGOF(res_siena_gof).
Value
A violin plot showing the distribution of statistics from the simulations and a line joining points showing the observed statistics.
References
Hintze, J. L. and Nelson, R. D. 1998. "Violin plots: A box plot-density trace synergism". The American Statistician, 52:181–184. doi:10.1080/00031305.1998.10480559
See Also
Other MoNAn:
plot_convergence
Other RSiena:
plot_interp
Other ergm:
plot_convergence
Examples
plot(monan_gof)
plot(siena_gof, cumulative = TRUE)
plot(ergm_gof, statistic = "espart")
Easily graph networks with sensible defaults
Description
This function provides users with an easy way to graph (m)any network data for exploration, investigation, inspiration, and communication.
graphr() builds upon {ggplot2} and {ggraph} to offer
pretty, easy, and extensible graphing solutions.
Just passing the function some network data
will often be sufficient to return a reasonable-looking graph.
The function also makes it easy to modify many of the most
commonly adapted aspects of a graph,
including node and edge size, colour, and shape,
as arguments rather than additional functions that you need to remember.
These can be defined outright, e.g. node_size = 8, or
in reference to an attribute of the network, e.g. node_size = "wealth".
Lastly, graphr() uses {ggplot2}-related theme information, so
it is easy to make colour palette and fonts institution-specific and consistent.
See e.g. theme_iheid() for more.
To learn more about what can be done visually,
try run_tute("Visualisation").
Usage
graphr(
.data,
layout = NULL,
labels = TRUE,
node_color,
node_shape,
node_size,
node_group,
edge_color,
edge_size,
isolates = c("legend", "caption", "keep"),
snap = FALSE,
label_dist = NULL,
label_repel = TRUE,
edge_bundle = FALSE,
backbone = NULL,
.shared = NULL,
...,
node_colour,
edge_colour
)
Arguments
.data |
A manynet-consistent object. |
layout |
An igraph, ggraph, or manynet layout algorithm.
If not declared, defaults to "configuration" for networks of up to
six nodes, "levels" for connected multilevel networks,
"layered" for other two mode networks,
and "stress" for all other networks.
For "layered" layout, one can further split graph by
declaring the "center" argument as the "events", "actors",
or by declaring a node name.
For "concentric" layout algorithm please declare the "membership" as an
extra argument.
The "membership" argument expects either a quoted node attribute present
in data or vector with the same length as nodes to draw concentric circles.
For "levels" layout algorithm one may declare the "level"
as extra argument.
The "level" argument expects either a quoted node attribute present
in data or vector with the same length as nodes to hierarchically
order categories.
If "level" is missing, the levels are taken from a 'lvl' node attribute
where there is one, or else from the two modes of a two mode network.
The layered layouts ("layered", "lineage", "railway" and "ladder")
accept a "ranks" argument, which takes either one of the methods named
at |
labels |
Which nodes to label, if the network is labelled.
Where a length-one string could mean more than one of these,
a node attribute is preferred to a measure, and a measure to a node name.
A single number is always read as a depth of ranks rather than as one
node's position, so a lone node is best named, as in |
node_color, node_colour |
Node variable to be used for coloring the nodes. It is easiest if this is added as a node attribute to the graph before plotting. Nodes can also be colored by declaring a color instead. |
node_shape |
Node variable to be used for shaping the nodes. It is easiest if this is added as a node attribute to the graph before plotting. Nodes can also be shaped by declaring a shape instead. |
node_size |
Node variable to be used for sizing the nodes. This can be any continuous variable on the nodes of the network. Since this function expects this to be an existing variable, it is recommended to calculate all node-related statistics prior to using this function. Nodes can also be sized by declaring a numeric size or vector instead. |
node_group |
Node variable to be used for grouping the nodes.
It is easiest if this is added as a hull over
groups before plotting.
Group variables should have a minimum of 3 nodes,
if less, number groups will be reduced by
merging categories with lower counts into one called "other".
A membership vector can also be given here.
Where nodes belong to several groups at once, as they can to several
cliques, give a membership matrix instead: one row for each node,
one column for each group, and a one wherever the node belongs to
the group. One hull is then drawn for each column, and the hulls
overlap where the groups do.
A measure that returns such a matrix, such as
|
edge_color, edge_colour |
Tie variable to be used for coloring the nodes. It is easiest if this is added as an edge or tie attribute to the graph before plotting. Edges can also be colored by declaring a color instead. |
edge_size |
Tie variable to be used for sizing the edges. This can be any continuous variable on the nodes of the network. Since this function expects this to be an existing variable, it is recommended to calculate all edge-related statistics prior to using this function. Edges can also be sized by declaring a numeric size or vector instead. |
isolates |
Character scalar, how to treat isolates. "keep" will keep isolates in the graph as they are. "legend" (default) will remove isolates from the graph but note them in the legend. "caption" will remove isolates from the graph but note them in the caption. If there are no isolates, this argument will be ignored. If the default layout ("stress") is used, we recommend that the "legend" option is used to avoid isolates crowding out the giant component. |
snap |
Logical scalar, whether the layout should be snapped to a grid. Where the network repeats a structure, as a lattice does, the two steps it repeats are mapped onto the axes, which draws it as a rectangle of rows and columns. Where it does not, each node moves to the nearest vacant grid point. Layouts that already carry meaning in their coordinates, such as "layered" or "scaling", are left as they are. |
label_dist |
Numeric scalar, in points (pt), controlling the extra
gap left between labels and node borders – similar to |
label_repel |
Logical scalar, whether labels should be repelled away
from each other and from nodes using |
edge_bundle |
Edge bundling, off by default ( |
backbone |
How to treat the network's backbone: the ties that a local
null model keeps, because they carry more weight, or sit in more
triangles, than chance alone would put there.
Where a backbone is used, those ties are drawn as the shortest, so that
the layout pulls apart the groups they hold together, and every tie is
still drawn, with the ties the filter does not keep faded well back.
This is what to reach for when a network is dense enough to draw as a
hairball.
By default ( |
.shared |
Internal. A list of the aesthetic ranges and categories found
across a list of networks, which |
... |
Extra arguments to pass on to the layout algorithm, if necessary. |
Value
A ggplot2::ggplot() object.
The last plot can be saved to the file system using ggplot2::ggsave().
See Also
Other mapping:
check_layout,
completion,
layout_concentric(),
layout_configuration(),
layout_correspondence(),
layout_layered(),
layout_levels(),
layout_matching(),
layout_scaling(),
layout_valence(),
plot_graphs,
plot_grapht
Examples
graphr(ison_adolescents)
ison_adolescents |>
mutate(color = rep(c("introvert","extrovert"), times = 4),
size = ifelse(netrics::node_is_cutpoint(ison_adolescents), 6, 3)) |>
mutate_ties(ecolor = rep(c("friends", "acquaintances"), times = 5)) |>
graphr(node_color = "color", node_size = "size",
edge_size = 1.5, edge_color = "ecolor")
graphr(ison_southern_women, labels = TRUE, label_dist = 10)
graphr(ison_southern_women, labels = TRUE, label_repel = FALSE)
# Label a selection of the nodes rather than all of them
graphr(ison_southern_women, labels = 2)
graphr(ison_southern_women, labels = "betweenness")
graphr(ison_adolescents, labels = c("Alice", "Betty"))
graphr(manynet::generate_random(40, 0.1), edge_bundle = TRUE)
graphr(manynet::generate_random(80, 0.2), backbone = TRUE)
Easily graph a set of networks with sensible defaults
Description
This function provides users with an easy way to graph lists of network data for comparison.
It builds upon this package's graphr() function,
and inherits all the same features and arguments.
See graphr() for more.
However, it uses the {patchwork} package to plot the graphs
side by side and, if necessary, in successive rows.
This is useful for lists of networks that represent, for example,
ego or component subgraphs of a network,
or a list of a network's different types of tie or across time.
By default just the first and last network will be plotted,
but this can be overridden by the "waves" parameter.
Where the graphs are of the same network (same nodes), the graphs may share a layout to facilitate comparison. By default, successive graphs will use the layout calculated for the "first" network, but other options include the "last" layout, or a mix, "both", of them.
Usage
graphs(netlist, waves, based_on = c("first", "last", "both"), ...)
Arguments
netlist |
A list of manynet-compatible networks.
This can also be a single manynet network object that encodes time,
which will be split automatically (as in |
waves |
Numeric, the number of plots to be displayed side-by-side. If missing, the number of plots will be reduced to the first and last when there are more than four plots. This argument can also be passed a vector selecting the waves to plot. |
based_on |
Whether the layout of the joint plots should be based on the "first" or the "last" network, or "both". |
... |
Additional arguments passed to |
Value
Multiple ggplot2::ggplot() objects displayed side-by-side.
See Also
Other mapping:
check_layout,
completion,
layout_concentric(),
layout_configuration(),
layout_correspondence(),
layout_layered(),
layout_levels(),
layout_matching(),
layout_scaling(),
layout_valence(),
plot_graphr,
plot_grapht
Examples
#graphs(to_egos(ison_adolescents))
#graphs(to_egos(ison_adolescents), waves = 8)
#graphs(to_egos(ison_adolescents), waves = c(2, 4, 6))
#graphs(play_diffusion(ison_adolescents))
Easily animate dynamic networks with sensible defaults
Description
This function provides users with an easy way to graph dynamic network data for exploration and presentation.
It builds upon this package's graphr() function,
and inherits all the same features and arguments.
See graphr() for more.
However, it uses the {gganimate} package to animate the changes
between successive iterations of a network.
This is useful for networks in which the ties and/or the node or tie
attributes are changing, including networks whose node composition
changes over time: every node that ever appears is assigned a stable
position, and nodes fade in and out in place as they enter and exit
the network.
By default node positions transition smoothly between waves using
the dynamic stress layout from {graphlayouts}
(graphlayouts::layout_as_dynamic()), which anchors each wave's
layout to a reference layout of the aggregate network.
The alpha argument controls this trade-off:
0 lets each wave's layout follow that wave's structure freely,
while 1 freezes every node at its aggregate position.
When another layout is requested,
a single static layout is computed on the aggregate
(union of waves) network instead, so that positions remain constant.
Unlike graphr(), grapht() uses this dynamic stress layout by default
even for two-mode networks (rather than a layered layout, which would
collapse many nodes onto a line); the two modes remain distinguishable
by node shape.
For networks with more than 30 nodes, node labels are suppressed by
default to keep frames legible; pass labels = TRUE to force them.
grapht() returns a {ggplot2}-compatible object that can be
extended with additional layers such as ggplot2::labs(),
ggplot2::theme(), scale functions, and others,
just like plots produced by graphr() and graphs().
The animation is rendered when the object is printed or displayed.
Users who want more control over animation parameters can call
gganimate::animate() directly on the returned object.
The visual appearance is consistent with graphr():
nodes use fillable shapes with the fill aesthetic,
the same colour palettes are applied,
directed networks receive arrowheads,
signed networks distinguish positive from negative ties by linetype,
and labels use the current theme font.
Legends transition along with the mapped aesthetics.
A progress bar is shown if it takes some time to encode all the .png files into a .gif.
Usage
grapht(
tlist,
layout = NULL,
labels = TRUE,
node_color,
node_shape,
node_size,
edge_color,
edge_size,
isolates = c("keep", "fade"),
alpha = 0.5,
label_dist = NULL,
label_repel = TRUE,
keep_isolates = NULL,
...,
node_colour,
edge_colour
)
## S3 method for class 'grapht'
print(x, ...)
Arguments
tlist |
A manynet-compatible network listed according to
a time attribute, waves, or slices.
This can also be a single manynet network object that encodes time,
which will be split automatically:
longitudinal or changing networks are split into waves via
|
layout |
An igraph, ggraph, or manynet layout algorithm.
If not declared, defaults to "configuration" for networks of up to
six nodes, "levels" for connected multilevel networks,
"layered" for other two mode networks,
and "stress" for all other networks.
For "layered" layout, one can further split graph by
declaring the "center" argument as the "events", "actors",
or by declaring a node name.
For "concentric" layout algorithm please declare the "membership" as an
extra argument.
The "membership" argument expects either a quoted node attribute present
in data or vector with the same length as nodes to draw concentric circles.
For "levels" layout algorithm one may declare the "level"
as extra argument.
The "level" argument expects either a quoted node attribute present
in data or vector with the same length as nodes to hierarchically
order categories.
If "level" is missing, the levels are taken from a 'lvl' node attribute
where there is one, or else from the two modes of a two mode network.
The layered layouts ("layered", "lineage", "railway" and "ladder")
accept a "ranks" argument, which takes either one of the methods named
at |
labels |
Which nodes to label, if the network is labelled.
Where a length-one string could mean more than one of these,
a node attribute is preferred to a measure, and a measure to a node name.
A single number is always read as a depth of ranks rather than as one
node's position, so a lone node is best named, as in |
node_color, node_colour |
Node variable to be used for coloring the nodes. It is easiest if this is added as a node attribute to the graph before plotting. Nodes can also be colored by declaring a color instead. |
node_shape |
Node variable to be used for shaping the nodes. It is easiest if this is added as a node attribute to the graph before plotting. Nodes can also be shaped by declaring a shape instead. |
node_size |
Node variable to be used for sizing the nodes. This can be any continuous variable on the nodes of the network. Since this function expects this to be an existing variable, it is recommended to calculate all node-related statistics prior to using this function. Nodes can also be sized by declaring a numeric size or vector instead. |
edge_color, edge_colour |
Tie variable to be used for coloring the nodes. It is easiest if this is added as an edge or tie attribute to the graph before plotting. Edges can also be colored by declaring a color instead. |
edge_size |
Tie variable to be used for sizing the edges. This can be any continuous variable on the nodes of the network. Since this function expects this to be an existing variable, it is recommended to calculate all edge-related statistics prior to using this function. Edges can also be sized by declaring a numeric size or vector instead. |
isolates |
One of |
alpha |
A number between 0 and 1 controlling the stability of
node positions across waves when the default dynamic (stress) layout
is used. 0 computes each wave's layout freely,
1 fixes all nodes at their aggregate-network positions.
By default 0.5. Passed to |
label_dist |
Numeric scalar, in points (pt), controlling the extra
gap left between labels and node borders – similar to |
label_repel |
Logical scalar, whether labels should be repelled away
from each other and from nodes using |
keep_isolates |
Deprecated. Use |
... |
Extra arguments to pass on to the layout algorithm, if necessary. |
x |
A grapht object to print. |
Details
Unlike graphr(), grapht() does not use ggrepel-based label
repelling (there is no straightforward way to repel labels consistently
across animation frames), so label_repel here instead toggles a fixed
offset nudging labels away from their nodes, and label_dist scales the
size of that nudge rather than being used as repel padding.
labels can select which nodes to label here too, and the selection is
resolved once over all the waves so that the same nodes stay labelled from
frame to frame. Unlike graphr(), though, animations of more than 30 nodes
default to no labels at all rather than to a selection of them.
Some further graphr() features are not available in animations:
node_group hulls, edge bundling, curved arcs for reciprocated ties,
and self-loops (loops are not drawn; a note is printed if present).
Note too that, where no layout is named, grapht() defaults to
the "stress" layout for every network rather than choosing one by
the network's shape as graphr() does,
so that nodes move smoothly from one wave to the next.
A layout named explicitly is still used, computed on the aggregate network.
Value
A {ggplot2}-compatible object with {gganimate} animation layers.
This object can be extended with additional {ggplot2} layers
(e.g. + labs(subtitle = "My subtitle")).
When printed or displayed, the animation is rendered as a .gif.
For more control over animation parameters,
pass the result to gganimate::animate() directly.
Source
https://blog.schochastics.net/posts/2021-09-15_animating-network-evolutions-with-gganimate/
See Also
Other mapping:
check_layout,
completion,
layout_concentric(),
layout_configuration(),
layout_correspondence(),
layout_layered(),
layout_levels(),
layout_matching(),
layout_scaling(),
layout_valence(),
plot_graphr,
plot_graphs
Examples
# A dynamic signed network of shifting European alliances 1872-1918,
# split automatically into snapshots of the ties active in each spell.
# Wrapped in \donttest{} because rendering the animation to a .gif is
# slow, not because the code is unsafe to run.
grapht(irps_wwi)
Plotting effects interpretation
Description
These functions support the interpretation of network and behavior effects
found in stochastic actor-oriented models.
They are S3 plotting methods for objects of class "selectionTable"
or "influenceTable", created using RSiena::selectionTable()
or RSiena::influenceTable(), respectively.
They plot how the evaluation function for selection or influence
changes based on ego's value and alter's value of some covariate.
This helps to interpret the effect of that covariate on the network dynamics
or behavior dynamics, respectively.
Usage
## S3 method for class 'selectionTable'
plot(x, quad = TRUE, separation = 0, ...)
## S3 method for class 'influenceTable'
plot(x, separation = 0, ...)
Arguments
x |
An object of class "selectionTable" or "influenceTable",
created using |
quad |
When TRUE (the default), a quadratic function
(average and total alter) is plotted.
Use |
separation |
This can be used to make the curves visually distinguishable if they overlap too much without it. An advisable value then is, e.g., 0.01. |
... |
Other arguments to be passed. |
Details
These functions were originally written by Tom Snijders, and adapted
for use in the {autograph} package.
Value
A plot showing how the selection/influence evaluation function changes based on ego's value and alter's value of some covariate.
Author(s)
Tom Snijders
Thanks to Steffen Triebel and Rene Veenstra for corrections.
References
For plotting selection tables, please consult the RSiena manual, Sections 13.1 and 13.3.
For plotting selection tables, please consult the RSiena manual, Sections 13.2 and 13.4.
See Also
Other RSiena:
plot_gof
Examples
plot(siena_selection)
plot(siena_selection) + ggplot2::scale_colour_discrete()
plot(siena_influence)
Objects exported from other packages
Description
These objects are imported from other packages. Follow the links below to see their documentation.
- dplyr
- ggplot2
aes(),element_blank(),element_text(),geom_point(),geom_smooth(),ggplot(),ggsave(),ggtitle(),guides(),labs(),scale_colour_hue(),scale_size(),scale_x_continuous(),theme(),theme_grey(),unit,xlab(),ylab()
Checking colours for colour blindness, print, and legibility
Description
These functions report how a set of colours holds up for viewers with colour vision deficiency (CVD), which affects about 8% of men and 0.5% of women, and for readers who see the plot in greyscale or at a distance.
simulate_colorblind() returns what a set of colours looks like to a viewer with
a given type of colour blindness, or in greyscale.
check_separation() scores how far apart colours are, taking the worst case
over normal vision and each type of colour blindness,
so that a palette is only credited for a difference that every viewer
can see.
check_contrast() scores whether text can be read on a ground.
Usage
simulate_colorblind(
colors,
type = c("deutan", "protan", "tritan", "grey", "normal"),
severity = 1
)
check_separation(colors, background = NULL)
check_contrast(colors, background = NULL)
Arguments
colors |
One or more colours, given as hexcodes or as names R knows. |
type |
The type of colour blindness to simulate: "deutan" (green-blind, the most common), "protan" (red-blind), "tritan" (blue-blind), "grey" for greyscale, as a photocopier renders it, or "normal" for unaffected vision. |
severity |
How severe the colour blindness is, between 0 and 1. By default 1, which is dichromacy. A value between 0 and 1 is anomalous trichromacy. Ignored for the "grey" and "normal" types. |
background |
Optionally, a colour to include in the comparison, so that a colour too pale or too dark to be seen against it is not counted as distinct. By default the current theme's background is used. |
Details
The three functions answer three different questions,
and a palette needs all three answered.
check_separation() asks whether two marks can be told apart,
check_contrast() asks whether text can be read on what it sits on,
and the "grey" simulation asks whether either survives a photocopier.
Simulation uses the matrices of Machado, Oliveira and Fernandes (2009),
applied in linear RGB.
Those matrices are published for each severity of colour blindness;
severity interpolates between the identity and the full-severity matrix,
which approximates the published steps closely enough for a check.
Full severity is dichromacy (deuteranopia, protanopia, tritanopia);
a lower severity is anomalous trichromacy (deuteranomaly, protanomaly),
which is the more common condition.
Greyscale conversion takes the relative luminance of the colour,
the same quantity check_contrast() scores with.
Distances are Euclidean distances in CIELAB space, the same measure
match_color() uses.
As a rule of thumb, a distance below 10 means two colours are easily
confused, 10 to 25 means they are separable but close,
and above 25 means they are comfortably distinct.
Ratios are those of WCAG 2.1, which asks for at least 4.5 for body text
and at least 3 for large text and for graphical objects.
Value
simulate_colorblind() returns a vector of hexcodes as long as colors.
check_separation() returns a square matrix of worst-case distances,
with the colours as its dimnames and a missing diagonal,
so that min(x, na.rm = TRUE) gives the closest pair.
A "grey" attribute holds the same matrix as seen in greyscale.
check_contrast() returns a square matrix of WCAG contrast ratios,
shaped the same way.
References
Machado, Gustavo M., Manuel M. Oliveira, and Leandro A. F. Fernandes. 2009. "A Physiologically-Based Model for Simulation of Color Vision Deficiency". IEEE Transactions on Visualization and Computer Graphics 15(6): 1291-98. doi:10.1109/TVCG.2009.113
World Wide Web Consortium. 2018. Web Content Accessibility Guidelines (WCAG) 2.1. https://www.w3.org/TR/WCAG21/
See Also
Other themes:
list_fonts(),
theme_medium,
theme_set
Examples
simulate_colorblind(c("#d73027", "#4575b4"), "deutan")
# A milder deuteranomaly, and the same colours in greyscale
simulate_colorblind(c("#d73027", "#4575b4"), "deutan", severity = 0.5)
simulate_colorblind(c("#d73027", "#4575b4"), "grey")
# How well does the current theme's palette separate five categories?
check_separation(ag_qualitative(5))
# The closest pair in it
min(check_separation(ag_qualitative(5)), na.rm = TRUE)
# And the closest pair once it is printed in greyscale
min(attr(check_separation(ag_qualitative(5)), "grey"), na.rm = TRUE)
# A red and a green that only look different to some viewers
check_separation(c("#B7352D", "#627313"))[1, 2]
# Can the current theme's ink be read on its ground?
check_contrast(ag_ink())[1, 2]
Matching colors across palettes
Description
Sometimes a palette or particular colours are chosen to symbolise or
represent a particular idea,
such as red for "stop" or green for "go",
or to convey some other interpretation.
Yet institutional palettes do not necessarily include all colours,
which can constrain how interpretable visualisations are under
institutional branding requirements.
match_color() helps to find the closest matching colours in a given palette
to one or more input colours.
There is also a helper function, is_dark(), to determine whether a color
is dark or light, which can be useful when deciding whether to use white or
black text on top of a colored background.
Usage
match_color(colors, pal)
is_dark(colors)
Arguments
colors |
One or more hexcodes to match with colors from the palette. |
pal |
Optionally, a vector of hexcodes representing a palette in which to find matches. By default, the current theme's qualitative palette is used. |
Details
This function uses the Euclidean distance of colours in CIELAB space to those of a target palette to find the closes corresponding colours. It also ensures that each input color is matched to a unique color in the palette. If there are more input colors than unique colors in the palette, an error is returned.
By default, the current theme's qualitative palette is used,
but any vector of hexcodes can be passed to the pal argument.
Value
A vector of hexcodes the length of the first argument.
Examples
match_color("#4575b4")
is_dark(c("#000","#FFF"))
Setting the medium a plot is made for
Description
A theme says how a plot should look.
A medium says where it will be seen, which is a separate question:
the same institutional theme serves a figure worked on at a desk,
projected in a lecture theatre, printed in an article,
and read on a phone, but each of those wants a different size of text
and, in one case, a different ground.
stocnet_medium() sets the medium for all subsequent plots,
as stocnet_theme() sets the theme, and leaves the theme alone.
If no medium is specified (i.e. the function is called without argument), the current medium is reported. The default medium is "screen".
Usage
stocnet_medium(medium = NULL, persist = FALSE)
set_stocnet_medium(medium = NULL, persist = FALSE)
ag_size()
Arguments
medium |
String naming a medium. By default "screen". The following media are currently available: screen, presentation, mobile, print. This string can be capitalised or not. |
persist |
Logical, by default FALSE.
If TRUE, the medium is remembered across sessions,
by writing it to the user's configuration directory
(see |
Details
The media available are:
"screen", the default, which draws as
{autograph}always has."presentation", which enlarges text by half, for a figure read from the back of a room.
"mobile", which enlarges text further, for a figure read in a narrow column on a handheld screen. Keep such a figure to one point, with few categories: a legend of more than about seven keys, or more than about three panels from
graphs(), will not survive the width."print", which leaves text at its usual size but draws on white, whatever ground the theme prefers. A dark or tinted ground costs ink and is often not reproduced.
The medium scales text, not marks.
Node sizes are relative to the layout they sit in,
so enlarging them without enlarging the layout would crowd it.
Where a figure needs larger nodes as well, set node_size in graphr().
The medium does not set the size of the file written.
Give ggplot2::ggsave() the width, height and resolution the medium
calls for as well.
Value
stocnet_medium() sets the medium to be used across all
stocnet packages. The medium is written to an option and held there.
ag_size() returns the multiplier the current medium applies to text
sizes, which is 1 unless the medium says otherwise.
See Also
Other themes:
list_fonts(),
theme_colorblind,
theme_set
Examples
stocnet_medium("presentation")
ag_size()
stocnet_medium("screen")
Setting a consistent theme for all plots
Description
This function enables plots to be quickly, easily and consistently themed. This is achieved by setting a theme option, usually at the start of an R session, that enables the palette to be used for all autograph-consistent plotting methods. This includes thematic colours for backgrounds, highlights, sequential, divergent and categorical colour schemes. The function sets these palettes to options that are then used by the various plotting functions.
If no theme is specified (i.e. the function is called without argument),
the current theme is reported.
The default theme is "default".
This theme uses a white background, blue and red for
highlighting, and a blue-white-red divergent palette.
The themes can be changed at any time by calling stocnet_theme()
or its alias set_stocnet_theme() with a different theme name.
Other themes include those based on the colour schemes of various universities, including ETH Zurich, UZH, UNIBE, RUG, and Oxford. Other themes include "bw" for black and white, "crisp" for a high-contrast black and white theme, "neon" for a dark theme with neon highlights, and "rainbow" for a colourful theme. The "clay" theme follows the palette and fonts used in the slides and documents that Anthropic's Claude produces: an ivory background, a slate ink base, and a clay orange highlight. Most themes are designed to be colour-blind safe.
Usage
stocnet_theme(theme = NULL, persist = FALSE)
set_stocnet_theme(theme = NULL, persist = FALSE)
Arguments
theme |
String naming a theme. By default "default". The following themes are currently available: default, bw, crisp, neon, clay, iheid, ethz, uzh, rug, unibe, oxf, unige, cmu, iast, hwu, rainbow. This string can be capitalised or not. |
persist |
Logical, by default FALSE.
If TRUE, the theme is remembered across sessions,
by writing it to the user's configuration directory
(see |
Value
This function sets the theme and palette(s) to be used across all stocnet packages. The palettes are written to options and held there.
Fonts
Some themes also set a preferred font for use in plots,
if available on the system (a check is performed).
In some cases, this includes a vector of options to try in sequence.
If none of the preferred fonts are available, a sans-serif font is used.
Themes then look much more alike than they should,
since the typeface carries a good deal of an institution\'s identity.
Call list_fonts() to see which font families R can currently see,
and ag_font() to see which one the current theme settled on.
To make more fonts available, there are two steps.
Install the font on your computer. Many of the fonts these themes prefer are free: Google Fonts (https://fonts.google.com) offers Roboto, Open Sans, Source Sans 3, Source Serif 4, Noto Serif, Montserrat, and Playfair Display, among others. Download the family, then install it as you would any other font: double-click the files and choose "Install" on Windows, open them in Font Book on macOS, or copy them into
~/.local/share/fontsand runfc-cache -fon Linux. Some fonts are licensed and are only available to members of the institution concerned, or for purchase; the theme falls back to a near relative where it can.Make the font available to R. Install the
{systemfonts}package and the fonts installed on your system are found directly, with no further step. Otherwise, useextrafont::font_import()once andextrafont::loadfonts()in each session. Restart R after installing a font, then calllist_fonts()to check that the family is now listed, and set the theme again.
Note that a font is only used where the graphics device can draw it.
The {ragg} devices (for example ragg::agg_png()) and {svglite} are
the most reliable;
the default PDF device needs the font embedded,
for which extrafont::embed_fonts() is available.
Custom
If you have specific needs or preferences, you can
set your own palettes or overwrite part of an existing one using options().
For example, to set a custom base color, you can use:
options(snet_highlight = c("#1b9e77", "#d95f02", "#7570b3")).
This will set a custom highlight color palette.
Similarly, you can set snet_div for divergent palettes
and snet_cat for categorical palettes.
See Also
Other themes:
list_fonts(),
theme_colorblind,
theme_medium
Examples
stocnet_theme("default")
plot(netrics::node_by_degree(ison_karateka))
stocnet_theme("uzh")
plot(netrics::node_by_degree(ison_karateka))