简体   繁体   中英

how to make a network based on correlation?

I have a matrix like below

data <- replicate(30, rnorm(30)) 

I would like to make a network like this image http://www.forwardprogress.net/data-steps-effective-relationship-marketing-dean-delisle/

of course the name of the variables (in this case V1 to V30 appeared)

is there any way to do it in R?

Thanks

You're question is quite unspecific. But something like this should get you started:

# Generate some toy data
data <- replicate(30, rnorm(30)) 

library("igraph")  # Load the igraph package

corr <- cor(data)  # Create weighted adjencency/correlation matrix

# Create a weighted complete graph from the correlation matrix
g <- graph.adjacency(corr, mode = "undirected", weighted = TRUE, diag = FALSE)

# Chose the layout function
custom.layout <- function(g, ...) {
  # layout.drl(g, weights = E(g)$weight, ...) # For bigger graphs
  layout.fruchterman.reingold(g, weights = E(g)$weight, ...)
}

Take a look at ?layout.fruchterman.reingold and the other layout functions to tweak the layout.

# Format edges
E(g)$cor <- E(g)$weight
E(g)$weight <- abs(E(g)$cor)
E(g)$color <- ifelse(E(g)$cor < 0, "blue", "red")
E(g)$width <- 3*atanh(E(g)$weight)

# Format vertices
V(g)$size <- 3*abs(rowSums(corr))
V(g)$color <- "grey"
V(g)$label.color <- "black"
V(g)$label <- ""

# Do the plot
plot(g, layout = custom.layout)

Imgur

Now it doesn't look very much like the graph you present. First, we don't expect any "hubs" due to the way we simulate our toy data---everything is just noise. Secondly, the layout is highly dependent on the layout function. Third, this was just to give you the idea of how to customise the graph and layout.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM