Relevance network diagram
date: 2023.10.12
Collection and organization of tutorials: Xiao Du’s biographical notes
Learn, summarize, and share!
Graphics of this tutorial
Write in front
Correlation analysis was also mentioned in the previous tutorials. However, there is no similar tutorial for using R language to draw correlation network diagrams, except for using the ggcor
package for mean analysis. In this tutorial, I also collected related packages and tutorials and drew corresponding graphics respectively. This tutorial is also worth collecting. The current code can basically be pasted and copied directly.
1 Install and load related R packages
library(ggraph) library(tidygraph) # install.packages("devtools") #devtools::install_github("Hy4m/linkET", force = TRUE) library("linkET") packageVersion("linkET") packageVersion("igraph") #devtools::install_github("Hy4m/netET") library(netET)
Set path
setwd("E:\Xiao Du's biographical notes\2023\20231012-mental analysis network diagram")
2 Load data
matrix_data(list(mtcars = mtcars)) matrix_data(list(mtcars = mtcars)) %>% as_md_tbl() as_matrix_data(mtcars) head(mtcars)
3 Calculate r value and p value
as_md_tbl(mtcars) correlate(mtcars) %>% as_md_tbl()
4 Drawing
4.1 Draw intra-group correlation heat map
Intra-group correlation analysis, we have mainly published in the previous tutorial. For details, please see R Language Visualization-Exquisite Graphic Drawing Series-Intra-group Correlation Analysis. We also provide complete code for outputting P values and cor values.
correlate(mtcars) %>% as_md_tbl() %>% qcorrplot() + geom_square()
Early tutorial code to calculate intra-group correlation
library(reshape2) library(corrplot) library(plyr) library(igraph) library(autoReg) library(tidyverse) library(ggsci) library(stats) ## Details can be viewed in this tutorial corr <- cor(mtcars, method = "spearman")
corrplot(corr,title = "", method = "circle", #or"circle" (default), "square", "ellipse", "number", "pie", "shade" and \ "color" outline = T, addgrid.col = "darkgray", order="hclust", addrect = 4, #hclust is clustered into 4 categories and adjusted according to the specific situation of the data mar = c(4,0,4,0), rect.col = "black", rect.lwd = 2, cl.pos = "b", tl.col = "black", tl.cex = 1, cl.cex = 1.5, tl.srt=60)
corrplot(corr,order = "AOE",type="upper",tl.pos = "tp") corrplot(corr, title = "", method = "number", outline = T, add = TRUE, type = "lower", order="AOE", # col="black", #diag=FALSE, tl.pos="n", cl.pos="n") ## Note: This step will report an error when running in R MarkDown format, but it can run normally in non-R MarkDown format.
The codes for outputting correlation p-values and corr values are as follows:
4.1 Draw correlation heat map between groups
The same intra-group correlation analysis has also been published in previous tutorials. For details, please see R Language Visualization-Exquisite Graphic Drawing Series-Inter-Group Correlation Analysis.
4.2.1 Loading data
First, use the code in the tutorial to calculate and run.
library(vegan) data("varespec") data("varechem")
dim(varespec) varespec[1:10,1:10]
View data
dim(varechem) varechem[1:10,1:10]
4.2.2 Calculate the correlation between two data
Draw a correlation heatmap
correlate(varespec[1:30], varechem) %>% qcorrplot() + geom_square() + scale_fill_gradientn(colours = RColorBrewer::brewer.pal(11, "RdBu"))
qcorrplot(varespec[1:30], type = "lower") + geom_square() + scale_fill_gradientn(colours = RColorBrewer::brewer.pal(11, "RdBu"))
5 Perform mantel analysis
mantel correlation analysis, early tutorial ggcor package drawing | correlation heat map | mental analysis chart.
Then it is very convenient to use the linkET
package.
5.1 Loading data
##mantel test library(dplyr) data("varechem", package = "vegan") data("varespec", package = "vegan")
5.2 View data
## View data dim(varespec) # [1] 24 44 varespec[1:10,1:10]
dim(varechem) # [1] 24 14 varechem[1:10,1:10]
5.3 Calculating network relationships
mantel <- mantel_test(varespec, ## Categorical data varechem, ## impact factor data ## The following code is analyzed and calculated based on varespec (categorical data) spec_select = list(Spec01 = 1:7, Spec02 = 8:18, Spec03 = 19:37, Spec04 = 38:44)) %>% mutate(rd = cut(r, breaks = c(-Inf, 0.2, 0.4, Inf), labels = c("< 0.2", "0.2 - 0.4", ">= 0.4")), pd = cut(p, breaks = c(-Inf, 0.01, 0.05, Inf), labels = c("< 0.01", "0.01 - 0.05", ">= 0.05")))
View data
head(mantel) ### > head(mantel) # A tibble: 6 × 6 spec env r p rd pd <chr> <chr> <dbl> <dbl> <fct> <fct> 1 Spec01 N 0.256 0.015 0.2 - 0.4 0.01 - 0.05 2 Spec01 P 0.137 0.093 < 0.2 >= 0.05 3 Spec01 K 0.400 0.004 >= 0.4 < 0.01 4 Spec01 Ca 0.0113 0.427 < 0.2 >= 0.05 5 Spec01 Mg 0.0263 0.366 < 0.2 >= 0.05 6 Spec01 S 0.275 0.021 0.2 - 0.4 0.01 - 0.05
5.3 Draw mantel analysis chart
## Draw correlation heatmap D0 <- qcorrplot(correlate(varechem), type = "lower", diag = FALSE) + geom_square() + ## Shape of correlation heat map ## geom_couple(aes(colour = pd, size = rd), data = mantel, curvature = nice_curvature()) + ## Color parameter adjustment scale_fill_gradientn(colours = RColorBrewer::brewer.pal(11, "RdBu")) + scale_size_manual(values = c(0.5, 1, 2)) + scale_colour_manual(values = color_pal(3)) + guides(size = guide_legend(title = "Mantel's r", override.aes = list(colour = "grey35"), order = 2), color = guide_legend(title = "Mantel's p", override.aes = list(size = 3), order = 1), fill = guide_colorbar(title = "Pearson's r", order = 3)) D0 ggsave("Mental correlation network diagram.jpg",width = 6, height = 6)
6 Network correlation diagram
This tutorial comes from Lingc TONG
‘s tweet. The original tutorial link shows the network correlation between microorganisms and environmental factors based on netET and ggraph.
6.1 Data preparation
Just use the previous data here.
devtools::install_github("Hy4m/netET", force = TRUE) #Load package library(ggraph) library(tidygraph) library(netET)
library(vegan) data("varespec") data("varechem")
6.2 Calculate correlation and extract drawing information
p1 <- correlate(varechem, varespec, method = "spearman") |> as_tbl_graph(abs(r) > 0.5, p < 0.05) # Calculate the degree centrality of the node degree_centrality <- degree(p1) # Calculate the degree centrality of the node degree_centrality <- degree(p1, mode = "all") # Add the centrality value to p1 p1$Degree <- degree_centrality p1 <- p1 |> mutate(Degree = degree_centrality)
Note: At the beginning, when I used the original code to extract information, I kept getting errors. Later, it is prompted that the version of the igraph
package is too high and you need to use the > 0.2
version package. Been tossing around here for a while. In the end, the version of this package is still downgraded.
Steps:
- Delete the existing
igraph
package - Reinstall the
igraph
package and limit the version
install.packages("igraph",version = '0.1.7')
Use the original code:
### Concise code p1 <- correlate(varechem, varespec, method = "spearman") |> as_tbl_graph(abs(r) > 0.5, p < 0.05) |> mutate(Degree = centrality_degree())
> p1 # A tbl_graph: 58 nodes and 30 edges # # An undirected simple graph with 36 components # # A tibble: 58 × 2 name degree <chr> <dbl> 1 N 2 2 P 1 3 K 1 4 Ca 2 5 mg 2 6 S 0 # ? 52 more rows # ? Use `print(n = ...)` to see more rows # # A tibble: 30 × 4 from to r p <int> <int> <dbl> <dbl> 1 13 18 0.608 0.00163 2 1 20 -0.606 0.00168 3 7 26 -0.500 0.0128 # ? 27 more rows # ? Use `print(n = ...)` to see more rows
xy <- layout_on_circle(p1) head(xy)
> head(xy) [,1] [,2] [1,] 1.0000000 0.0000000 [2,] 0.9941380 0.1081190 [3,] 0.9766206 0.2149704 [4,] 0.9476532 0.3193015 [5,] 0.9075754 0.4198891 [6,] 0.8568572 0.5155539
6.3 Draw a circular correlation diagram
D1 <- ggraph(p1, xy) + #geom_edge_fan(aes(colour = r > 0), width = 0.75, linetype="dashed") + #width Change line thickness geom_edge_fan(aes(colour = r > 0), width = 0.8) + geom_node_point(aes(size = Degree), color = "#fa8c35") + scale_edge_colour_manual(values = c("TRUE" = "#c93756", "FALSE" = "#21a675"),#R>0, is TRUE labels = c("Negative", "Positive")) + geom_node_text(aes(x = 1.07 * x, y = 1.07 * y, label = name, angle = node_angle(x, y)), hjust = "outward", data = function(data) dplyr::filter(data, Degree > 0)) + expand_limits(x = c(-1.5, 1.5), y = c(-1.5, 1.5)) + # coord_fixed(clip = "off") + theme(panel.background = element_blank()) + labs(edge_colour = "Spearman's r") ggsave("ring network diagram.jpg", width = 6, height = 6)
6.4 Bipartite network diagram
p2 <- correlate(varechem, varespec, method = "spearman") |> as_tbl_graph(abs(r) > 0.5, p < 0.05) |> mutate(Degree = centrality_degree()) |> as_bipartite_circular(outer_nodes = names(varespec)) p2
Drawing
D2 <- ggraph(p2, layout_bipartite_circular(p2)) + annotate_arc_rect(0, 180, fill = "#e0eee8", r0 = 0.55, r1 = 1.05) + geom_edge_circular(aes(colour = r > 0), edge_width = 0.75, edge_alpha = 0.8) + geom_node_point(aes(size = Degree, color = Degree == 0)) + geom_node_text_circular(expand = 0.08) + scale_colour_manual(values = c("TRUE" = "grey55","FALSE" = "#065279"), guide = "none") + scale_edge_colour_manual(values = c("TRUE" = "#c93756", "FALSE" = "#21a675"), labels = c("Negative", "Positive")) + coord_fixed(clip = "off", xlim = c(-1.2, 1.2), ylim = c(0, 1.1)) + theme(panel.background = element_blank()) + guides(edge_colour = guide_legend(override.aes = list(edge_width = 1))) + labs(edge_colour = "Spearman's r") D2 ggsave("Bipartite network diagram.jpg", width = 8, height = 8)
7 Merge graphics
library(patchwork) library(cowplot) D0 + D1 + D2 + plot_layout(nrow = 1, ncol = 3, widths = c(6,5,6)) ggsave("20231012.jpg", width = 20, height = 10)
Previous articles:
1. Column series of recurring SCI articles
2. “Instructions for Subscribing to the Bio-Information Knowledge Base” is updated simultaneously and is easy to search and manage.
3. The most complete WGCNA tutorial (replace the data to get all the results and graphics)
-
WGCNA analysis | Full process analysis code | Code 1
-
WGCNA analysis | Full process analysis code | Code 2
-
WGCNA analysis | Full process code sharing | Code 3
4. Beautiful graphics drawing tutorial
- Beautiful graphics drawing tutorial
5. Transcriptome Analysis Tutorial
Transcriptome upstream analysis tutorial [zero basic]
Xiao Du’s Bioinformatics Notes mainly publishes or collects bioinformatics tutorials, as well as R-based analysis and visualization (including data analysis, graphic drawing, etc.); shares interesting literature and learning materials! !