How to create a network graph with DiagrammeR? - r

I have a large dataset but let's put a toy example:
mydata <- data.table(from=c("John", "John", "Jim"),to=c("John", "Jim", "Jack"))
nodesd=unique(c(mydata$from, mydata$to))
nodes <- create_node_df( n=length(nodesd), label=nodesd, type=nodesd)
edges <- create_edge_df(from = mydata$from, to = mydata$to, rel = "leading_to")
graph <- create_graph( nodes_df = nodes, edges_df = edges)
render_graph(graph)
But I get this:
Instead of the expected result:
I got that one using first igraph, but I'd like to avoid that step.
UPDATE:
library(data.table)
mydata <- data.table(from=c("John", "John", "Jim"),to=c("John", "Jim", "Jack"), stringsAsFactors = T)
mydata is already using factors. I don't need extra steps converting factors.
I can create the plot with igraph:
library(igraph)
mygraph <- graph_from_data_frame(d=mydata, directed=T)
plot(mygraph)
Or use its object to build a DiagrammeR plot:
V(mygraph)$label = V(mygraph)$name
V(mygraph)$name = factor(V(mygraph)$name, levels=as.character(V(mygraph)$name))
mygraph2 <- from_igraph(mygraph)
render_graph(mygraph2)
But now I try to do it directly from Diagrammer, without igraph:
nodesd = unique(unlist(mydata[,.(from,to)]))
nodes <- create_node_df( n=length(nodesd), label=nodesd)
edges <- create_edge_df(from = mydata$from, to = mydata$to, rel = "leading_to")
graph <- create_graph( nodes_df = nodes, edges_df = edges)
render_graph(graph)
What's the problem?

With your 1st code I got:
> mydata <- data.table(from=c("John", "John", "Jim"),to=c("John", "Jim", "Jack"))
> nodesd=unique(c(mydata$from, mydata$to))
> nodes <- create_node_df( n=length(nodesd), label=nodesd, type=nodesd)
> edges <- create_edge_df(from = mydata$from, to = mydata$to, rel = "leading_to")
Warning messages:
1: In create_edge_df(from = mydata$from, to = mydata$to, rel = "leading_to") :
NAs introduced by coercion
2: In create_edge_df(from = mydata$from, to = mydata$to, rel = "leading_to") :
NAs introduced by coercion
> graph <- create_graph( nodes_df = nodes, edges_df = edges)
> render_graph(graph)
As #user20650 said, it is an issue with character and factors. So I make a change.
mydata <- data.frame(from=c("John", "John", "Jim"),
to=c("John", "Jim", "Jack"))
mydata$from <- as.character(mydata$from)
mydata$to <- as.character(mydata$to)
nodesd = unique(c(mydata$from, mydata$to))
nodes <- create_node_df( n=length(nodesd), label=nodesd, type=nodesd)
edges <- create_edge_df(from = factor(mydata$from, levels = nodesd),
to = factor(mydata$to, levels = nodesd),
rel = "leading_to")
graph <- create_graph(nodes_df = nodes, edges_df = edges)
render_graph(graph)
I got the result below.
Result:
I hope it can help.

Related

Overriding "Non-Existent Components" in a Loop

I have the following network graph:
library(tidyverse)
library(igraph)
set.seed(123)
n=15
data = tibble(d = paste(1:n))
relations = tibble(
from = sample(data$d),
to = lead(from, default=from[1]),
)
graph = graph_from_data_frame(relations, directed=T, vertices = data)
V(graph)$color <- ifelse(data$d == relations$from[1], "red", "orange")
plot(graph, layout=layout.circle, edge.arrow.size = 0.2)
I learned how to remove all the "edges" in this graph:
g <- graph-E(graph)
plot(g)
Now, I am trying to do this same thing, but using a "loop" instead:
for (i in 1:15)
for (j in 1:15) {
graph <- graph - edge(paste0(i, "|", j))
}
But I think the problem is that the above code is trying to delete "edges" that exist, and this code does not have the ability to "skip" (override) an instance when it is commanded to delete a non-existing edge:
Error in delete_edges(e1, unlist(e2, recursive = FALSE)) :
At iterators.c:1828 : Cannot create iterator, invalid edge id, Invalid vertex id
Is there a way to instruct this "loop" to "skip" every instances where two edges do not have a connection and to continue until the loop is done?
Thank you!
I don't know why you want to run a for loop, but please find below a possible solution using the as_edgelist() function from the igraph library.
Reprex
Your data
library(igraph)
library(dplyr)
set.seed(123)
n=15
data = tibble(d = paste(1:n))
relations = tibble(
from = sample(data$d),
to = lead(from, default=from[1]),
)
graph = graph_from_data_frame(relations, directed=T, vertices = data)
V(graph)$color <- ifelse(data$d == relations$from[1], "red", "orange")
plot(graph, layout=layout.circle, edge.arrow.size = 0.2)
Suggested code
edgelist <- as_edgelist(graph, names = TRUE)
for (i in 1:15) {
graph <- graph - edge(paste0(edgelist[i,1], "|", edgelist[i,2]))
}
plot(graph)
Created on 2022-02-24 by the reprex package (v2.0.1)

R: Display "popup" information when mouse hovers over (graph) visnetwork

I simulated some data and created a graph network in R using visnetwork:
library(igraph)
library(dplyr)
library(visNetwork)
#create file from which to sample from
x5 <- sample(1:100, 1100, replace=T)
#convert to data frame
x5 = as.data.frame(x5)
#create first file (take a random sample from the created file)
a = sample_n(x5, 1000)
#create second file (take a random sample from the created file)
b = sample_n(x5, 1000)
#combine
c = cbind(a,b)
#create dataframe
c = data.frame(c)
#rename column names
colnames(c) <- c("a","b")
#create graph
graph <- graph.data.frame(c, directed=F)
graph <- simplify(graph)
plot(graph)
fc <- fastgreedy.community(graph)
V(graph)$community <- fc$membership
library(visNetwork)
nodes <- data.frame(id = V(graph)$name, title = V(graph)$name, group = V(graph)$community)
nodes <- nodes[order(nodes$id, decreasing = F),]
edges <- get.data.frame(graph, what="edges")[1:2]
#visnet graph
visNetwork(nodes, edges) %>% visIgraphLayout(layout = "layout_with_fr") %>%
visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE)
Right now, the graph only displays node information when you click on it. Suppose if each node had observed properties in the "original file". E.g.
#add some information corresponding to the original data
other_damages_in_dollars <- rnorm(1000,104,9)
location <- c("canada","usa")
location <- sample(location, 1000, replace=TRUE, prob=c(0.3, 0.7))
type_of_house <- c("single","townhome", "rental" )
type_of_house<- sample(type_of_house , 1000, replace=TRUE, prob=c(0.5, 0.3, 0.2))
#heres how the original data would have looked like
original_data = data.frame(a,b, other_damages_in_dollars, location, type_of_house)
Is there a way to add this information when you click on each node?
#visnet graph - is it possible to use the '$' operator to add these properties?
visNetwork(nodes, edges) %>% visIgraphLayout(layout = "layout_with_fr") %>%
%>% visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE)visEvents(selectEdge = "function(properties) { alert(this.body.data.edges._data[properties.edges[0]].original_data$location); }") %>% visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE)visEvents(selectEdge = "function(properties) { alert(this.body.data.edges._data[properties.edges[0]].original_data$type_of_house); }") %>% visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE)visEvents(selectEdge = "function(properties) { alert(this.body.data.edges._data[properties.edges[0]].original_data$other_damage_in_dollars); }")
You don't need an event. This is built into many of the vis.js elements.
So, I'll start with designing the content of my tooltip. Of the 1000 rows you made of location, home types, and costs, I created a subset with the same number of rows as there are nodes. This is what will be shown in my tooltip.
newTitle = paste0("Location: ", toupper(location[1:nrow(nodes)]),
"<br>Home Type: ", type_of_house[1:nrow(nodes)],
"<br>Damage Related Costs: ",
sprintf("$%.2f", other_damages_in_dollars[1:nrow(nodes)]))
#check it; looks okay
Now I'm going to make my tooltips the titles of my nodes.
# replace the node titles:
nodes$title = newTitle
Call the network and click anywhere on the graph once to activate it. Now you just have to hover....(note the blue box, that means it's listening). There are a lot of nodes really close together, so there will be a bit of delayed response when you move from node to node.
You can get rid of the need to click to activate with visOptions(clickToUse = F).
visNetwork(nodes, edges) %>% visIgraphLayout(layout = "layout_with_fr")
FYI
I didn't go through all of the code in the original question; there's a lot! I'm going to include what I ran before creating my graph, so you know what was in and what was not. This code is not changed from your question.
library(igraph)
library(dplyr)
library(visNetwork)
#create file from which to sample from
x5 <- sample(1:100, 1100, replace=T)
#convert to data frame
x5 = as.data.frame(x5)
#create first file (take a random sample from the created file)
a = sample_n(x5, 1000)
#create second file (take a random sample from the created file)
b = sample_n(x5, 1000)
#combine
c = cbind(a,b)
#create dataframe
c = data.frame(c)
#rename column names
colnames(c) <- c("a","b")
#create graph
graph <- graph.data.frame(c, directed=F)
graph <- simplify(graph)
fc <- fastgreedy.community(graph)
V(graph)$community <- fc$membership
nodes <- data.frame(id = V(graph)$name, title = V(graph)$name, group = V(graph)$community)
nodes <- nodes[order(nodes$id, decreasing = F),]
edges <- get.data.frame(graph, what="edges")[1:2]
#add some information corresponding to the original data
other_damages_in_dollars <- rnorm(1000,104,9)
location <- c("canada","usa")
location <- sample(location, 1000, replace=TRUE, prob=c(0.3, 0.7))
type_of_house <- c("single","townhome", "rental" )
type_of_house<- sample(type_of_house , 1000, replace=TRUE, prob=c(0.5, 0.3, 0.2))
#heres how the original data would have looked like
original_data = data.frame(a,b, other_damages_in_dollars, location, type_of_house)

R igraph cluster nodes with the same colour (feature)

# example data
library(igraph)
links <- cbind.data.frame(from = rep("A", 6),
to = LETTERS[1:6],
weight = rep((1:3), each =2))
nodes <- nodes <- cbind.data.frame(id = LETTERS[1:6],
feature = rep((1:3), each =2))
net <- graph_from_data_frame(d = links, vertices = nodes, directed = T)
V(net)$color <- V(net)$feature
plot(net, vertex.size=30, edge.arrow.size = 0)
This is what I get:
What I want is to cluster the same colored nodes together, something similar as shown in the figure below. How can I do it?
Maybe the option mark.groups in plot could help
plot(net,mark.groups = split(V(net)$name,V(net)$color))
which gives

Combining/Merging two graphs in igraph

I created the following two graphs using igraph:
t1terms <- c("fire",
"people",
"residents",
"victims",
"affected",
"please",
"can",
"london",
"support",
"survivors")
t1labels <- as.vector(t1terms)
g<-graph.full(n=10, directed = FALSE, loops = FALSE) %>%
set_vertex_attr("label", value = t1labels)
t2terms <- c("fire",
"victims",
"says",
"people",
"cladding",
"police",
"may",
"will",
"dead",
"theresa")
t2labels <- as.vector(t2terms)
g1<-graph.full(n=10, directed = FALSE, loops = FALSE) %>%
set_vertex_attr("label", value = t2labels)
I can't figure out how to merge the two graphs without duplicating common nodes. I really appreciate some help. I tried 'graph.union', but it didn't work.
Thank you,
Chamil
Use igraph's built-in conventions and make the vertex labels into each's name:
V(g)$name <- V(g)$label
V(g1)$name <- V(g1)$label
Grab the attributes and edge list of each graph and rbind() them together, creating a combination attribute data.frame and combination edge list data.frame while ensuring that you're only keeping unique() vertices:
attrs <- rbind(as_data_frame(g, "vertices"), as_data_frame(g1, "vertices")) %>% unique()
el <- rbind(as_data_frame(g), as_data_frame(g1))
Use attrs and el to make your new graph:
new_g <- graph_from_data_frame(el, directed = FALSE, vertices = attrs)
You can get the union by turning each graph into an edgelist, joining the edgelists and the making that into a graph.
EL = matrix(get.vertex.attribute(g, "label")[get.edgelist(g)], ncol=2)
EL1 = matrix(get.vertex.attribute(g1, "label")[get.edgelist(g1)], ncol=2)
ELU = rbind(EL, EL1)
ELU = ELU[!duplicated(ELU),]
GU = graph_from_edgelist(ELU, directed=FALSE)
## To check the result
par(mfrow=c(1,3))
plot(g)
plot(g1)
plot(GU)

How to change node color in Diagrammer

I have diagram and want to add variety of colors to the nodes, so I added this code line from grviz that change node color from the value he has node = "[fillcolor = red]Canis" but it didn't change anything in diagram.
The rest code for diagram:
df <- data.frame(col1 = c( "Cat", "Dog", "Bird"),
col2 = c( "Feline", "Canis", "Avis"),
stringsAsFactors=FALSE)
uniquenodes <- unique(c(df$col1, df$col2))
library(DiagrammeR)
nodes <- create_node_df(n=length(uniquenodes), nodes = seq(uniquenodes), type="number", label=uniquenodes, nodes = "[fillcolor = red]Canis")
edges <- create_edge_df(from=match(df$col1, uniquenodes), to=match(df$col2, uniquenodes), rel="related")
g <- create_graph(nodes_df=nodes, edges_df=edges, attr_theme = NULL)
render_graph(g)

Resources