Reputation: 2890
I was wondering if it is possible to plot a tidygraph object with a single node? For example, if I create some data and a tidygraph object with 2 nodes, that would look like this:
library(tidygraph)
library(graph)
nodes <- data.frame(name = c('var1', 'var2'), value = c(3, 10))
edges <- data.frame(from = c(1),
to = c(2))
tg <- tbl_graph(nodes = nodes, edges = edges)
ggraph(tg, "partition") +
geom_node_tile(aes(fill = name)) +
scale_y_reverse() +
theme_void()
However, I was wondering if I could plot a tidygraph object that contains just 1 node. For example, if my data had no edge data associated with it, like so:
nodes <- data.frame(name = c('var1'), value = c(3))
tg <- tbl_graph(nodes = nodes)
When I try to plot the above, I get the error:
Error in layout[, 1] : incorrect number of dimensions
Which makes sense because there is no edge data. I, naively, tried to set the edge data to something like:
edges <- data.frame(from = c(1),
to = c(1))
But this throws back an error as well.
I was wondering if there is a way to achieve what Im trying to do?
Upvotes: 1
Views: 165
Reputation: 173858
You could create a two-row node data frame with the same row repeated twice, the same for the edges data frame. Create the plot object and remove the second row of its data component.
library(tidygraph)
#> Attaching package: 'tidygraph'
#> The following object is masked from 'package:stats':
#>
#> filter
library(ggraph)
#> Loading required package: ggplot2
nodes <- data.frame(name = c('var1'), value = c(3, 3))
edges <- data.frame(from = c(1, 1),
to = c(1, 1))
tg <- tbl_graph(nodes = nodes, edges = edges)
p <- ggraph(tg, "partition") +
geom_node_tile(aes(fill = name)) +
scale_y_reverse() +
theme_void()
#Remove second node
p$data <- p$data[-2, ]
p
Created on 2022-03-28 by the reprex package (v2.0.1)
Upvotes: 1