流程图(一)利用python绘制弦图

发布于:2024-12-18 ⋅ 阅读:(57) ⋅ 点赞:(0)

流程图(一)利用python绘制弦图

弦图(Chord diagram)简介

1

数据围绕一个圆呈放射状排列,显示不同实体之间的相互关系,这既是弦图。弦图通过每个圆弧的大小比例表示连接分配数值,可以用颜色将数据分成不同类别以助于比较和区分。缺点则是当连接过多时会显得混乱。

快速绘制

  1. 基于bokeh

    首先需要安装holoviews:pip install holoviews

    然后安装最新的bokeh即可:pip install --upgrade bokeh

    import pandas as pd
    import holoviews as hv
    from holoviews import opts, dim
    from bokeh.sampledata.les_mis import data
    
    hv.extension('bokeh')
    hv.output(size=300)
    
    # 导入数据
    nodes = hv.Dataset(pd.DataFrame(data['nodes']), 'index')
    links = pd.DataFrame(data['links'])
    
    # 绘制弦图
    chord = hv.Chord((links, nodes)).select(value=(5, None))
    chord.opts(
        opts.Chord(cmap='Category20', edge_cmap='Category20', edge_color=dim('source').str(), 
                   labels='name', node_color=dim('index').str()))
    

    2

  2. 基于pyecharts

    import requests
    import json
    from pyecharts import options as opts
    from pyecharts.charts import Graph
    
    # 获取官方的数据
    url = "https://raw.githubusercontent.com/pyecharts/pyecharts-gallery/master/Graph/les-miserables.json"
    
    response = requests.get(url)
    j = json.loads(response.text)
    nodes = j["nodes"]
    links = j["links"]
    categories = j["categories"]
    
    
    c = (
        Graph(init_opts=opts.InitOpts(width="1000px", height="600px"))
        .add(
            "",
            nodes=nodes,
            links=links,
            categories=categories,
            layout="circular",
            is_rotate_label=True,
            linestyle_opts=opts.LineStyleOpts(color="source", curve=0.3),
            label_opts=opts.LabelOpts(position="right"),
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(title="悲惨世界角色关系"),
            legend_opts=opts.LegendOpts(orient="vertical", pos_left="2%", pos_top="20%"),
        )
    )
    
    c.render_notebook()
    

    3

  3. 基于mne

    pip install -U mne
    pip install -U mne-connectivity
    pip install nibabel

    from mne_connectivity.viz import plot_connectivity_circle 
    import numpy as np
    
    # 自定义数据:随机连接的20个node
    N = 20
    node_names = [f"N{i}" for i in range(N)]
    
    # 随机连接
    ran = np.random.rand(N,N)
    con = np.where(ran > 0.9, ran, np.nan)  # 低于0.9的连接置为NaN
    
    # 绘制弦图
    fig, axes = plot_connectivity_circle(con, node_names) 
    

    4

    定制多样化的弦图

    自定义日历弦图一般是结合使用场景对相关参数进行修改,并辅以其他的绘图知识。参数信息可以通过官网进行查看,其他的绘图知识则更多来源于实战经验,大家不妨将接下来的绘图作为一种学习经验,以便于日后总结。

    1. 修改node_angles实现弦图分割

      from mne_connectivity.viz import plot_connectivity_circle 
      import numpy as np
      
      # 自定义数据:随机连接的20个node
      N = 20
      node_names = [f"N{i}" for i in range(N)]
      
      # 随机连接
      ran = np.random.rand(N,N)
      con = np.where(ran > 0.9, ran, np.nan)  # 低于0.9的连接置为NaN
      
      # 自定义弧度
      start, end = 45, 135
      first_half = (np.linspace(start, end, len(node_names)//2) +90).astype(int)[::+1] %360
      second_half = (np.linspace(start, end, len(node_names)//2) -90).astype(int)[::-1] %360
      node_angles = np.array(list(first_half) + list(second_half))
      
      # 自定义参数node_angles
      fig, axes = plot_connectivity_circle(con, node_names, 
          node_angles=node_angles)
      

      5

    2. 自定义节点

      from mne_connectivity.viz import plot_connectivity_circle 
      import numpy as np
      
      # 自定义数据:随机连接的20个node
      N = 20
      node_names = [f"N{i}" for i in range(N)]
      
      # 随机连接
      ran = np.random.rand(N,N)
      con = np.where(ran > 0.9, ran, np.nan)  # 低于0.9的连接置为NaN
      
      # 自定义节点
      node_edgecolor = N//2 * [(0,0,0,0.)] + N//2 * ['green']
      node_colors = N//2 * ['crimson'] + N//2 * [(0,0,0,0.)]
      
      fig, axes = plot_connectivity_circle(con, node_names, 
      #     node_width=50, # 节点宽度
      #      vmin=0.97, vmax=0.99, # 显示连接的范围
      #      node_colors=node_colors, # 自定义节点颜色                            
      #      node_edgecolor=node_edgecolor, # 自定义节点颜边缘
           node_linewidth=2, # 自定义节点线宽
           colormap='Blues', 
           facecolor='white',
           textcolor='black',
           colorbar=False, 
           linewidth=10 # 连接线宽度                              
      )
      

      6

    总结

    以上通过bokeh、pyecharts和mne快速绘制弦图。并通过修改参数或者辅以其他绘图知识自定义各种各样的弦图来适应相关使用场景。

    共勉~


网站公告

今日签到

点亮在社区的每一天
去签到