Skip to main content

Plot a causal graph

Source: R/plot.R

Description

cgraph_plot() builds a plot of a cgraph, drawn with grid graphics when it is printed. Style it first with style_nodes(), style_edges(), style_labels(), label_nodes() and style_title(). The plotting article explains the layouts and every style field, with examples.

Usage

cgraph_plot(
  x,
  layout = NULL,
  main = NULL,
  asp = NA,
  outer_margin = grid::unit(2, "mm"),
  title_gap = grid::unit(1, "lines"),
  ...
)

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

Arguments

x A graph created with cgraph(), of any class.
layout

Where to place the nodes:

  • NULL (default): "sugiyama" for a DAG, "stress" otherwise.

  • A method name for cgraph_layout(). With "sugiyama", edges also follow the routes it computes; to use only its positions, pass cgraph_layout(x, "sugiyama") instead.

  • A function, called with x and ..., that returns a layout.

  • A data.frame with columns name, x, and y.

  • A named list of c(x, y) positions, e.g. list(A = c(0, 0), X = c(1, 0)).

main Optional plot title, styled with style_title().
asp Optional y/x aspect ratio. NA (default) fills the available space; asp = 1 makes one x-unit equal one y-unit.
outer_margin Grid unit for the outer margin. Default grid::unit(2, "mm").
title_gap Grid unit for the gap between title and graph. Default grid::unit(1, "lines").
... Passed to layout when it is a method name (e.g. direction or seed; see cgraph_layout()) or a function. For plot(), the arguments of cgraph_plot().

Details

Unstyled nodes, edges, labels and titles use the defaults set with plot_options(). plot(x, ...) is a shortcut for print(cgraph_plot(x, ...)).

Value

A cgraph_plot object, drawn when printed (plot() draws it and returns it invisibly). Printing it with newpage = FALSE draws it into the current grid viewport instead of a new page; cgraph_grob() gives its grid grob.

See Also

plot-styling for the style verbs, plot_options() to change the style defaults for every plot.

Other plotting: cgraph_grob(), cgraph_layout(), cgraph_plot_grid(), plot-styling, plot_default_options(), plot_options()

Examples

dag <- cgraph("A --> X + Y, X --> M --> Y")
cgraph_plot(dag, main = "A DAG") # "sugiyama" layout, the default for a DAG

cgraph_plot(dag, direction = "down")

cgraph_plot(dag, layout = "stress", seed = 1405)


# Style it step by step; it is drawn when printed
cgraph_plot(dag, main = "Styled DAG") |>
  style_nodes(fill = "lightblue", col = "navy") |>
  style_nodes(fill = "gold", nodes = "Y") |>
  style_edges(col = "gray40", lwd = 2) |>
  style_edges(col = "red", lwd = 3, from = "X", to = "M")