DiagrammeR v0.9.0


Monthly downloads



by Richard Iannone

Create Graph Diagrams and Flowcharts Using R

Create graph diagrams and flowcharts using R.


Travis-CI Build Status codecov.io

With the DiagrammeR package you can create, modify, analyze, and visualize network graph diagrams. A collection of functions are available for working specifically with graph objects. The output can be viewed in the RStudio Viewer, incorporated in RMarkdown, integrated into Shiny web apps, converted into other graph formats, or exported as image, PDF, or SVG files.

It's possible to make the above graph diagram using a combination of DiagrammeR functions strung together with the magrittr %>% pipe:


create_random_graph(140, 100, set_seed = 23) %>%
  join_node_attrs(get_w_connected_cmpts(.)) %>%
  select_nodes_by_id(get_articulation_points(.)) %>%
  set_node_attrs_ws("peripheries", 2) %>%
  set_node_attrs_ws("width", 0.65) %>%
  set_node_attrs_ws("height", 0.65) %>%
  set_node_attrs_ws("penwidth", 3) %>%
  clear_selection() %>%
    attr =
      c("color",  "penwidth", "width", "height"),
    value =
      c("gray80", "3",        "0.5",   "0.5"),
    attr_type =
      c("edge",   "edge",     "node",  "node")) %>%
    node_attr_from = "wc_component",
    node_attr_to = "fillcolor",
    alpha = 80) %>%
  set_node_attr_to_display() %>%
  select_nodes_by_degree("deg >= 3") %>%
  trav_both_edge() %>%
  set_edge_attrs_ws("penwidth", 4) %>%
  set_edge_attrs_ws("color", "gray60") %>%
  clear_selection() %>%

DiagrammeR's graph functions allow you to create graph objects, modify those graphs, get information from the graphs, create a series of graphs, perform scaling of attribute values with data values, and many other useful things.

This functionality makes it possible to generate a network graph with data available in tabular datasets. Two specialized data frames contain node data and attributes (node data frames) and edges with associated edge attributes (edge data frames). Because the attributes are always kept alongside the node and edge definitions (within the graph object itself), we can easily work with them and specify styling attributes to differentiate nodes and edges by size, color, shape, opacity, length, and more. Here are some of the available graph functions:

Network Graph Example

Let's create a property graph by combining CSV data that pertains to contributors to three software projects. The CSV files (contributors.csv, projects.csv, and projects_and_contributors.csv) are available in the DiagrammeR package. Together they provide the properties name, age, join_date, email, follower_count, following_count, and starred_count to the person nodes; project, start_date, stars, and language to the project nodes; and the contributor_role and commits properties to the edges.


# Create the main graph
graph <-
  create_graph() %>%
  set_graph_name("software_projects") %>%
      "extdata", "contributors.csv",
      package = "DiagrammeR"),
    set_type = "person",
    label_col = "name") %>%
      "extdata", "projects.csv",
      package = "DiagrammeR"),
    set_type = "project",
    label_col = "project") %>%
      "extdata", "projects_and_contributors.csv",
      package = "DiagrammeR"),
    from_col = "contributor_name",
    to_col = "project_name",
    ndf_mapping = "label",
    rel_col = "contributor_role")

We can always view the property graph with the render_graph() function.

render_graph(graph, output = "visNetwork")

Now that the graph is set up, you can create queries with magrittr pipelines to get specific answers from the graph.

Get the average age of all the contributors. Select all nodes of type person (not project). Each node of that type has non-NA age attribute, so, cache that attribute with cache_node_attrs_ws() (this function caches a vector of node attribute values in the graph). Get the cache straight away and get its mean (with get_cache() and then mean()).

graph %>% 
  select_nodes("type == 'person'") %>%
  cache_node_attrs_ws("age", "numeric") %>%
  get_cache() %>% 
#> [1] 33.6

We can get the total number of commits to all projects. We know that all edges contain the numerical commits attribute, so, select all edges (select_edges() by itself selects all edges in the graph) and cache the commits values as a numeric vector with cache_edge_attrs_ws() (this is stored in the graph object itself). Immediately extract the cached vector with get_cache() and get its sum() (all commits to all projects).

graph %>% 
  select_edges() %>%
  cache_edge_attrs_ws("commits", "numeric") %>%
  get_cache() %>%
#> [1] 5182

Single out the one known as Josh and get his total number of commits as a maintainer and as a contributor. Start by selecting the Josh node with select_nodes("name == 'Josh'"). In this graph, we know that all people have an edge to a project and that edge can be of the relationship (rel) type of contributor or maintainer. We can migrate our selection from nodes to outbound edges with trav_out_edges() (and we won't provide a condition, just all the outgoing edges from Josh will be selected). Now we have a selection of 2 edges. Get a vector of commits values as a stored, numeric vector with cache_edge_attrs_ws(). Immediately, extract it from the graph with get_cache() and get the sum(). This is the total number of commits.

graph %>% 
  select_nodes("name == 'Josh'") %>%
  trav_out_edge() %>%
  cache_edge_attrs_ws("commits", "numeric") %>%
  get_cache() %>% 
#> [1] 227

Get the total number of commits from Louisa, just from the maintainer role though. In this case we'll supply a condition in trav_out_edge(). This acts as a filter for the traversal, nullifying the selection to those edges where the condition is not met. Although there is only a single value in the cache, we'll still use sum() after get_cache() (a good practice because we may not know the vector length, especially in big graphs).

graph %>% 
  select_nodes("name == 'Louisa'") %>%
  trav_out_edge("rel == 'maintainer'") %>%
  cache_edge_attrs_ws("commits", "numeric") %>%
  get_cache() %>% 
#> [1] 236

How do we do something more complex, like, get the names of people in graph above age 32? First select all person nodes with select_nodes("type == 'person'"). Then, follow up with another select_nodes() call specifying age > 32, and, importantly using set_op = "intersect" (giving us the intersection of both selections). Now we have the selection of nodes we want; get all values of these nodes' name attribute as a cached character vector with the cache_node_attrs_ws() function. Get that cache and sort the names alphabetically with the R function sort().

graph %>% 
  select_nodes("type == 'person'") %>%
  select_nodes("age > 32", set_op = "intersect") %>%
  cache_node_attrs_ws("name", "character") %>%
  get_cache() %>%
#> [1] "Jack"   "Jon"    "Kim"    "Roger"  "Sheryl"

Another way to express the same selection of nodes is to use the mk_cond() (i.e., 'make condition') helper function to compose the selection conditions. It uses sets of 3 elements for each condition: (1) the node or edge attribute name (character value), (2) the conditional operator (character value), and (3) the non-attribute operand. A linking & or | between groups is used to specify ANDs or ORs. The mk_cond() helper is also useful for supplying variables to a condition for a number of select_...() and all trav_...() functions.

graph %>% 
      "type", "==", "person",
      "age",  ">",  32)) %>%
  cache_node_attrs_ws("name", "character") %>%
  get_cache() %>%
#> [1] "Jack"   "Jon"    "Kim"    "Roger"  "Sheryl"

That supercalc is progressing quite nicely. Let's get the total number of commits from all people to that most interesting project. Start by selecting that project's node and work backwards! Traverse to the edges leading to it with trav_in_edge(). Those edges are from committers and they all contain the commits attribute with numerical values. Cache those values, get the cache straight away, take the sum -> 1676 commits.

graph %>% 
  select_nodes("project == 'supercalc'") %>%
  trav_in_edge() %>%
  cache_edge_attrs_ws("commits", "numeric") %>%
  get_cache() %>% 
#> [1] 1676

How would we find out who committed the most to the supercalc project? This is an extension of the previous problem and there are actually a few ways to do this. We start the same way (at the project node, using select_nodes()), then:

  • traverse to the inward edges [trav_in_edge()]
  • cache the commits values found in these selected edges [cache_edge_attrs_ws()]
  • this is the complicated part but it's good: (1) use select_edges(); (2) compose the edge selection condition with the mk_cond() helper, where the edge has a commits value equal to the largest value in the cache; (3) use the intersect set operation to restrict the selection to those edges already selected by the trav_in_edge() traversal function
  • get a new cache of commits values (should only be a single value in this case)
  • we want the person responsible for these commits; traverse to that node from the edge selection [trav_out_node()]
  • cache the name values found in these selected nodes [cache_node_attrs_ws()]
  • get the cache [get_cache()]
graph %>% 
  select_nodes("project == 'supercalc'") %>%
  trav_in_edge() %>%
  cache_edge_attrs_ws("commits", "numeric") %>%
  select_edges(mk_cond("commits", "==", get_cache(.) %>% max()), "intersect") %>%
  cache_edge_attrs_ws("commits", "numeric") %>%
  trav_out_node() %>%
  cache_node_attrs_ws("name") %>%
#> [1] "Sheryl"

What is the email address of the individual that contributed the least to the randomizer project? (We shall try to urge that person to do more.)

graph %>% 
  select_nodes("project == 'randomizer'") %>%
  trav_in_edge() %>%
  cache_edge_attrs_ws("commits", "numeric") %>%
  trav_in_node() %>%
  trav_in_edge(mk_cond("commits", "==", get_cache(.) %>% min())) %>%
  trav_out_node() %>%
  cache_node_attrs_ws("email") %>%
#> [1] "the_will@graphymail.com"

Kim is now a contributor to the stringbuildeR project and has made 15 new commits to that project. We can modify the graph to reflect this. First, add an edge with add_edge(). Note that add_edge() usually relies on node IDs in from and to when creating the new edge. This is almost always inconvenient so we can instead use node labels (ensure they are unique!) to compose the edge, setting use_labels = TRUE. The rel value in add_edge() was set to contributor -- in a property graph we should try to always have values set for all node type and edge rel attributes. We will set another attribute for this edge (commits) by first selecting the edge (it was the last edge made: use select_last_edge()), then, use set_edge_attrs_ws() and provide the attribute/value pair. Finally, deselect all selections with clear_selection(). The graph is now changed, have a look.

graph <- 
  graph %>%
    from = "Kim",
    to = "stringbuildeR",
    rel = "contributor",
    use_labels = TRUE) %>%
  select_last_edge() %>%
  set_edge_attrs_ws("commits", 15) %>%

render_graph(graph, output = "visNetwork")

Get all email addresses for contributors (but not maintainers) of the randomizer and supercalc88 projects. Multiple select_nodes() calls in succession is an OR selection of nodes (project nodes selected can be randomizer or supercalc). With trav_in_edge() we just want the contributer edges/commits. Once on those edges, hop back unconditionally to the people from which the edges originate with trav_out_node(). Get the email values from those selected individuals as a sorted character vector.

graph %>% 
  select_nodes("project == 'randomizer'") %>%
  select_nodes("project == 'supercalc'") %>%
  trav_in_edge("rel == 'contributor'") %>%
  trav_out_node() %>%
  cache_node_attrs_ws("email", "character") %>%
  get_cache() %>% 
#> [1] "j_2000@ultramail.io"      "josh_ch@megamail.kn"     
#> [3] "kim_3251323@ohhh.ai"      "lhe99@mailing-fun.com"   
#> [5] "roger_that@whalemail.net" "the_simone@a-q-w-o.net"  
#> [7] "the_will@graphymail.com"

Which people have committed to more than one project? This is a matter of node degree. We know that people have edges outward and projects and edges inward. Thus, anybody having an outdegree (number of edges outward) greater than 1 has committed to more than one project. Globally, select nodes with that condition using select_nodes_by_degree("outdeg > 1"). Once getting the name attribute values from that node selection, we can provide a sorted character vector of names.

graph %>%
  select_nodes_by_degree("outdeg > 1") %>%
  cache_node_attrs_ws("name") %>%
  get_cache() %>% 
#> [1] "Josh"   "Kim"    "Louisa"


DiagrammeR is used in an R environment. If you don't have an R installation, it can be obtained from the Comprehensive R Archive Network (CRAN). It is recommended that RStudio be used as the R IDE to take advantage of its rendering capabilities and the code-coloring support for Graphviz and mermaid diagrams.

You can install the development (v0.9.0) version of DiagrammeR from GitHub using the devtools package.


Or, get the v0.8.4 release from CRAN.


Functions in DiagrammeR

Name Description
add_n_nodes Add one or several unconnected nodes to the graph
add_edges_w_string Add one or more edges using a text string
add_balanced_tree Add a balanced tree of nodes to the graph
add_edges_from_table Add edges and attributes to graph from a table
add_n_nodes_ws Add a multiple of new nodes with edges to or from one or more selected nodes
add_global_graph_attrs Add one or more global graph attributes
add_edge_df Add edges from an edge data frame to an existing graph object
add_full_graph Add a fully connected graph
add_edge Add an edge between nodes in a graph object
add_cycle Add a cycle of nodes to the graph
add_node_df Add nodes from a node data frame to an existing graph object
add_node Add a node to an existing graph object
add_prism Add a prism of nodes to the graph
add_path Add a path of nodes to the graph
add_nodes_from_table Add nodes and attributes to graph from a table
add_nodes_from_df_cols Add nodes from distinct values in data frame columns
cache_edge_attrs_ws Cache edge attributes (based on a selection of edges) in the graph
cache_edge_attrs Cache edge attributes in the graph
add_star Add a star of nodes to the graph
add_to_series Add graph object to a graph series object
cache_edge_count_ws Cache a count of edges (available in a selection) in the graph
colorize_node_attrs Apply colors based on node attribute values
do_bfs Perform the breadth-first search (bfs) algorithm
colorize_edge_attrs Apply colors based on edge attribute values
cache_node_attrs_ws Cache node attributes (based on a selection of nodes) in the graph
DiagrammeROutput Widget output function for use in Shiny
create_graph Create a graph object
drop_edge_attrs Drop an edge attribute column
create_edge_df Create an edge data frame
do_dfs Perform the depth-first search (dfs) algorithm
export_graph Export a graph to various file formats
from_adj_matrix Create a graph using an adjacency matrix
get_articulation_points Get articulation points
get_all_connected_nodes Get all nodes connected to a specified node
get_paths Get paths from a specified node in a directed graph
get_edge_ids Get a vector of edge ID values
get_edge_df Get an edge data frame from a graph
get_w_connected_cmpts Get all nodes associated with connected components
graph_count Count graphs in a graph series object
get_non_nbrs Get non-neighbors of a node in a graph
join_node_attrs Join new node attribute values using a data frame
rescale_node_attrs Rescale numeric node attribute values
combine_ndfs Combine multiple node data frames
rescale_edge_attrs Rescale numeric edge attribute values
layout_nodes_w_string Layout nodes using a text-based schematic
rename_node_attrs Rename a node attribute
render_graph_from_series Render a graph available in a series
generate_dot Generate DOT code using a graph object
copy_edge_attrs Copy an edge attribute column and set the name
from_igraph Convert an igraph graph to a DiagrammeR one
get_graph_name Get graph name
get_graph_time Get the graph date-time or timezone
is_graph_connected Is the graph a connected graph?
get_predecessors Get node IDs for predecessor nodes to the specified node
get_periphery Get nodes that form the graph periphery
is_graph_directed Is the graph a directed graph?
get_betweenness Get betweenness centrality scores
get_edge_attrs Get edge attribute values
get_eccentricity Get node eccentricities
get_bridging Get bridging scores
get_nbrs Get all neighbors of one or more nodes
get_node_attrs Get node attribute values
get_s_connected_cmpts Get nodes within strongly connected components
get_selection Get the current selection available in a graph object
mk_cond Helper for making conditions for some functions
mermaid R + mermaid.js
create_node_df Create a node data frame
cache_node_count_ws Cache a count of nodes (available in a selection) in the graph
cache_node_attrs Cache node attributes in the graph
create_random_graph Create a randomized graph
delete_global_graph_attrs Delete one of the global graph attributes stored within a graph object
join_edge_attrs Join new edge attribute values using a data frame
is_graph_empty Is the graph empty?
delete_node Delete a node from an existing graph object
recode_edge_attrs Recode a set of edge attribute values
recode_node_attrs Recode a set of node attribute values
select_edges_by_edge_id Select edges in a graph using edge ID values
select_nodes Select nodes in a graph
select_edges_by_node_id Select edges in a graph using node ID values
select_rev_edges_ws Select any reverse edges from a selection of edges
combine_edfs Combine multiple edge data frames into a single edge data frame
create_series Create a graph series object
combine_graphs Combine two graphs into a single graph
delete_edge Delete an edge from an existing graph object
create_subgraph_ws Create a subgraph based on a selection of nodes or edges
delete_edges_ws Delete all selected edges in an edge selection
edge_count Get count of all edges or edges with distinct relationship types
get_cmty_l_eigenvec Get community membership by leading eigenvector
drop_node_attrs Drop a node attribute column
get_cmty_louvain Get community membership by Louvain optimization
get_constraint Get constraint scores for one or more graph nodes
get_edges Get node IDs associated with edges
get_degree_distribution Get degree distribution data for a graph
edge_rel Create, read, update, delete, or report status of an edge relationship
grVizOutput Widget output function for use in Shiny
get_global_graph_attrs Get global graph attributes
export_csv Export a graph to CSV files
get_cmty_fast_greedy Get community membership by modularity optimization
get_cmty_edge_btwns Get community membership by edge betweenness
get_cmty_walktrap Get community membership using the Walktrap method
get_common_nbrs Get all common neighbors between two or more nodes
get_graph_from_series Get a graph available in a series
get_graph_diameter Get the graph diameter
get_similar_nbrs Get neighboring nodes based on node attribute similarity
graph_info Get metrics for a graph
get_successors Get node IDs for successor nodes to the specified node
trav_out_node Traverse from one or more selected edges onto adjacent, outward nodes
mutate_edge_attrs Mutate a set of edge attribute values
grViz R + viz.js
trav_out Traverse from one or more selected nodes onto adjacent, outward nodes
trigger_script Trigger a script embedded in a graph series object
visnetwork Render graph with visNetwork
mutate_node_attrs Mutate a set of node attribute values
node_present Determine whether a specified node is present in an existing graph object
renderGrViz Widget render function for use in Shiny
node_type Create, read, update, delete, or report status of a node type definition
replace_in_spec Razor-like template for diagram specification
series_info Get information on a graph series
set_cache Cache a vector in the graph
set_node_attrs Set node attributes
set_node_position Apply a layout position to a single node
image_icon Icons and their download locations
x11_hex X11 colors and hexadecimal color values
vivagraph Render graph with VivaGraphJS
trav_in Traverse from one or more selected nodes onto adjacent, inward nodes
trav_out_edge Traverse from one or more selected nodes onto adjacent, outward edges
nudge_node_positions_ws Move layout positions of a selection of nodes
render_graph Render the graph in various formats
%>% The magrittr pipe
renderDiagrammeR Widget render function for use in Shiny
select_last_node Select last node in a series of node IDs in a graph
set_global_graph_attrs Set global graph attributes
select_nodes_by_degree Select nodes in the graph based on their degree values
set_graph_name Set graph name
clear_selection Clear a selection of nodes or edges in a graph
delete_nodes_ws Delete all selected nodes in a node selection
create_complement_graph Create a complement of a graph
clear_global_graph_attrs Clear any global graph attributes that are set
copy_node_attrs Copy a node attribute column and set the name
DiagrammeR R + mermaid.js
edge_present Determine whether a specified edge is present in an existing graph object
edge_info Get detailed information on edges
get_degree_histogram Get histogram data for a graph's degree frequency
get_cache Get a cached vector from a graph object
get_jaccard_similarity Get Jaccard similarity coefficient scores
get_closeness Get closeness centrality values
get_dice_similarity Get Dice similarity coefficient scores
select_nodes_by_id Select nodes in a graph by ID values
set_graph_undirected Convert graph to an undirected graph
select_nodes_in_neighborhood Select nodes based on a walk distance from a specified node
set_graph_time Set graph date-time and timezone
select_edges Select edges in a graph
set_edge_attrs_ws Set edge attributes with an edge selection
set_edge_attrs Set edge attributes
select_last_edge Select last edge in a series of edges defined in a graph
trav_both_edge Traverse from one or more selected nodes onto adjacent edges
trav_in_node Traverse from one or more selected edges onto adjacent, inward nodes
trav_in_edge Traverse from one or more selected nodes onto adjacent, inward edges
trav_both Traverse from one or more selected nodes onto neighboring nodes
get_min_spanning_tree Get a minimum spanning tree subgraph
get_node_df Get a node data frame from a graph
get_node_ids Get a vector of node ID values
import_graph Import a graph from various graph formats
invert_selection Invert selection of nodes or edges in a graph
node_count Get count of all nodes or certain types of nodes
node_info Get detailed information on nodes
rev_edge_dir_ws Reverse the direction of selected edges in a graph
rename_edge_attrs Rename an edge attribute
remove_from_series Remove a graph from a graph series
rev_edge_dir Reverse the direction of all edges in a graph
set_node_attr_to_display Set the node attribute values to be rendered
set_node_attrs_ws Set node attributes with a node selection
subset_series Subset a graph series object
to_igraph Convert a DiagrammeR graph to an igraph one
No Results!

Last month downloads


Include our badge in your README