美文网首页生信绘图
ggraph绘制网络图(1)

ggraph绘制网络图(1)

作者: R语言数据分析指南 | 来源:发表于2021-05-16 19:54 被阅读0次

    最近有小伙伴问如何通过R绘制网络图,自己以前的确没有绘制网络图的需求,正好趁此机会学习一下,这篇文档介绍如何通过ggraph来绘制简单的网络图,后续还会有更多案例来展示,希望对大家有所帮助
    数据链接:https://mp.weixin.qq.com/s/kWqSk8oa17zySqMpDSJcdQ

    加载R包

    library(tidyverse)
    library(tidygraph)
    library(ggraph)
    

    自定义颜色

    colors <-c("#E41A1C","#1E90FF","#FF8C00","#4DAF4A","#984EA3",
               "#40E0D0","#FFC0CB","#00BFFF","#FFDEAD","#90EE90",
               "#EE82EE","#00FFFF","#F0A3FF", "#0075DC", 
               "#993F00","#4C005C","#2BCE48","#FFCC99",
               "#808080","#94FFB5","#8F7C00","#9DCC00",
               "#426600","#FF0010","#5EF1F2","#00998F",
               "#740AFF","#990000","#FFFF00")
    

    加载数据

    us417 <- read.csv("US417.csv", header=T)
    

    连接数据创建节点

    exports <- us417 %>% distinct(source) %>% rename(label = source)
    
    imports <- us417 %>% distinct(target) %>% rename(label = target)
    
    nodes <- full_join(exports, imports,by = "label") %>% 
      mutate(id = 1:nrow(nodes)) %>%
      select(id, everything())
    

    创建边文件

    edges <- us417 %>% 
      left_join(nodes, by = c("source" = "label")) %>% 
      rename(from = id)
    
    edges <- edges %>% 
      left_join(nodes, by = c("target" = "label")) %>% 
      rename(to = id)
    
    edges <- select(edges, from, to, weight)
    

    整合数据

    net.tidy <- tbl_graph(
      nodes = nodes, edges = edges, directed = TRUE
    )
    

    ggraph绘制网络图

    ggraph(net.tidy, layout = "star") + 
      geom_node_point(size=4,aes(color=label),
                      show.legend = F) +
      geom_edge_link(aes(width = weight,
                         color=weight),show.legend = F) + 
      scale_edge_width(range = c(0.5, 2)) +
      geom_node_text(aes(label = label),repel = TRUE) +
      scale_color_manual(values = colors)+
      theme_graph()
    

    相关文章

      网友评论

        本文标题:ggraph绘制网络图(1)

        本文链接:https://www.haomeiwen.com/subject/dserjltx.html