Skip to content

Instantly share code, notes, and snippets.

@juliasilge
Forked from dgrtwo/qgraph.R
Created December 16, 2016 05:30
Show Gist options
  • Save juliasilge/0d7d91772e978094bb74784fb6d0e116 to your computer and use it in GitHub Desktop.
Save juliasilge/0d7d91772e978094bb74784fb6d0e116 to your computer and use it in GitHub Desktop.
library(ggplot2)
library(igraph)
library(ggraph)
library(scales)
library(ggforce)
network_theme <- theme_no_axes() +
theme(panel.border = element_blank())
theme_set(network_theme)
qgraph <- function(x, ...) UseMethod("qgraph")
create_igraph <- function(x, directed = FALSE, vertices = NULL,
filter_vertices = TRUE) {
if (!is.null(vertices)) {
# filter for those in vertex data frame
x <- x[x[[1]] %in% vertices[[1]], ]
x <- x[x[[2]] %in% vertices[[1]], ]
if (filter_vertices) {
vertices <- vertices[vertices[[1]] %in% x[[1]] |
vertices[[1]] %in% x[[2]], ]
}
}
graph_from_data_frame(x, directed, vertices)
}
create_ggraph <- function(..., layout = "fr", seed = 2016) {
if (!is.null(seed)) {
set.seed(seed)
}
create_igraph(...) %>%
ggraph(layout = layout)
}
qgraph.data.frame <- function(x, directed = FALSE, vertices = NULL,
filter_vertices = TRUE, ...) {
qgraph(create_igraph(x, directed, vertices, filter_vertices), ...)
}
qgraph.igraph <- function(x,
node_color = "lightblue", node_size = 6,
layout = "fr",
repel = FALSE, check_overlap = FALSE, legend = TRUE,
seed = 2016, ...) {
set.seed(seed)
ret <- ggraph(x, layout = layout) +
geom_edge_link() +
geom_node_point(color = node_color, size = node_size)
if (repel) {
ret <- ret + geom_node_text(aes(label = name), repel = TRUE)
} else {
ret <- ret + geom_node_text(aes(label = name), check_overlap = check_overlap,
vjust = 1, hjust = 1)
}
ret <- ret + ggforce::theme_no_axes()
if (!legend) {
ret <- ret + theme(legend.position = "none")
}
ret
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment