#' Plot a directed graph with Fruchterman-Rheingold layout algorithm
#'
#' @param .graph a tbl_graph object with a node attribute eigen_centr_year
#' @param .save_plot FALSE by default. Select TRUE if plot should be saved
#' @param .filename the name of the saved plot. Don't forget to specify the device, e.g. '.pdf'
#'
#' @return a plot and, if .save_plot == TRUE, a file
#' @export
#'
#' @examples
#' g <- create_example_graph()
#' nodes.with.centr <- compute_eigen_centr_year(g)
#'
#' g2 <- g %>%
#' tidygraph::activate(nodes) %>%
#' tidygraph::left_join(nodes.with.centr)
#'
#' plot_directed_graph_with_fr(g2)
plot_directed_graph_with_fr <- function(.graph,
.save_plot = FALSE,
.filename = "directed_graph_with_fr.pdf",
.node_labels = FALSE,
.edge_labels = FALSE,
.remove_isolates = TRUE,
.remove_multiple_edges = FALSE){
g <- .graph %>%
tidygraph::activate(edges) %>%
tidygraph::mutate(exh_start_Y_from = factor(exh_start_Y_from)) %>%
(function(x){
if(.remove_multiple_edges == TRUE){
x %>% filter(!tidygraph::edge_is_multiple())
} else { x }
}) %>%
(function(x){
if(.remove_isolates == TRUE){
x %>% tidygraph::activate(nodes) %>% filter(!tidygraph::node_is_isolated())
} else { x }
})
p <- ggraph::ggraph(g, layout = "fr") +
ggraph::geom_edge_fan(arrow = arrow(length = unit(4, 'mm')),
end_cap = ggraph::circle(5.5, 'mm'),
aes(color = exh_start_Y_from)) +
ggraph::geom_edge_loop(aes(color = exh_start_Y_from, label = artist_id),
arrow = arrow(length = unit(4, 'mm')),
end_cap = ggraph::circle(5.5, 'mm')) +
ggraph::geom_node_point(aes(size = eigen_centr)) +
theme_minimal()
if(.node_labels == TRUE){p <- p + ggraph::geom_node_text(aes(label = name), repel = T)}
if(.edge_labels == TRUE){p <- p + ggraph::geom_edge_fan(aes(label = artist_id))}
if(.save_plot == TRUE){ggsave(filename = paste0("figures/", .filename), plot = p, width = 7, height = 5)}
return(p)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.