Reputation: 21
I am trying to plot network in R of a distance matrix where distances between the nodes should be proportion to the distance matrix value and node size should be proportion to the value for nodes.etworkin
Upvotes: 2
Views: 3347
Reputation: 41
one solution I found is make a two column data frame using the distance matrix and added to the networkD3 package. check this link https://www.jessesadler.com/post/network-analysis-with-r/
> linksdf
source target dist
1 6307 14749 1.334
2 6307 14778 1.334
3 6307 2089 1.329
4 6307 2690 1.341
> nodesdf
nodeID group
6307 6307 n
6336 6336 l
6438 6438 h
6439 6439 o
7046 7046 u
forceNetwork(Links = linksdf, Nodes = nodesdf, Source = "source",
Target = "target", NodeID = "nodeID", Group = "group")
Or you can use the distance matrix directly (https://www.r-graph-gallery.com/254-use-igraph-input-format-networkd3/):
library(igraph)
library(networkD3)
# Create data
data=matrix(sample(0:1, 400, replace=TRUE, prob=c(0.95,0.05) ), nrow=20)
# Tell Igraph it is an adjency matrix... with default parameters
network=graph_from_adjacency_matrix(data)
# transform Igraph format in something readable by networkD3
network=igraph_to_networkD3(network)
# plot
simpleNetwork(network$links,
height = 480, # height of frame area in pixels
width = 480,
linkDistance = 120, # distance between node. Increase this value to have more space between nodes
charge = -480, # numeric value indicating either the strength of the node repulsion (negative value) or attraction (positive value)
fontSize = 27, # size of the node names
linkColour = rgb(0.1,0.9,0.1,0.3),# colour of edges, MUST be a common colour for the whole graph
nodeColour = "forestgreen", # colour of nodes, MUST be a common colour for the whole graph
opacity = 0.9, # opacity of nodes. 0=transparent. 1=no transparency
)
hope it can help.
Upvotes: 2
Reputation: 6535
As CoffeeRain says, next time please provide code that shows your work and gives anyone trying to answer insight into your thought process and where the real problem may lie. Are you looking for something like this?
library(maps)
data(us.cities)
#create distance matrix
d <- dist(us.cities[, c("lat", "long")])
#multidimensional scaling so we can plot and retain distance relationships
foo <- cmdscale(d, k = 2)
#everything is upside down and backwards
#plot(foo)
plot(-foo)
plot(-foo, cex = scale(us.cities$pop))
Upvotes: 2