Python NetworkX:加权图中的边颜色

Python NetworkX: edges color in a weighted graph

我正在尝试使用 Python 中的 networkx 库绘制一个具有由高斯相似函数给出的边权重的完全连接图。当我绘制图表时,边缘的颜色强度似乎非常温和,我猜这是由于连接权重较小 (Half-moons fully connected graph )。但是,我想知道有没有办法让颜色强度更强。

我使用的代码:

import numpy as np
import matplotlib
from matplotlib import pyplot as plt
from sklearn import cluster, datasets
import networkx as nx

def eucledian_dist(x_i, x_j):
    coord = x_i.shape[0]
    d=[]
    if coord == x_j.shape[0]:
        for i in range(coord):
            d.append((x_i[i] - x_j[i])**2)
    return (np.sqrt(sum(d),dtype=np.float64))

def distance_matrix(data, distance_measure):
    Npts= data.shape[0]
    distance_matrix=np.zeros((Npts,Npts))
    for xi in range(Npts):
        for xj in range(Npts):
            distance_matrix[xi,xj] = distance_measure(data[xi],data[xj])
    return(distance_matrix)

def adjacency_matrix(data, sigma):
    dist_matrix = distance_matrix(data, eucledian_dist)
    adjacency_matrix= np.exp(-(dist_matrix)**2 /sigma)
    adjacency_matrix[adjacency_matrix==1] = 0
    return(adjacency_matrix)
    
#Generate data
Npts = 35
half_moons_data = datasets.make_moons(n_samples=Npts, noise=.040, random_state=1991)
nodes_coord = dict()
for key  in [i for i in range(Npts)]:
    nodes_coord[key] = list(half_moons_data[0][key])

#Compute adjancency matrix
W = adjacency_matrix(half_moons_data[0], sigma=0.05)

#Create graph:
nodes_idx = [i for i in range(Npts)]
graph = nx.Graph()
graph.add_nodes_from(nodes_idx)
graph.add_weighted_edges_from([(i,j, W[i][j])
                                   for i in range(Npts) for j in range(Npts)])
                                   
#Plot graph:
nx.draw_networkx_nodes(graph, nodes_coord, node_size=5, node_color="red") 
nx.draw_networkx_edges(graph, nodes_coord,
                               edge_cmap= plt.cm.Blues,
                               width=1.5, edge_color=[graph[u][v]['weight'] 
                                                      for u, v in graph.edges],
                               alpha=0.2)
plt.show()

我真的很感激任何 advice/feedback。

让我们使用数据的 edge_vmax 参数为边缘颜色的最大值添加一个上限:

nx.draw_networkx_edges(graph, nodes_coord,
                               edge_cmap= plt.cm.Blues,
                               width=1.5, edge_color=[graph[u][v]['weight'] 
                                                      for u, v in graph.edges],
                               alpha=.2,
                               edge_vmax=10e-30)

输出:

来自docs

edge_vmin,edge_vmax (floats) – Minimum and maximum for edge colormap scaling (default=None)

edge_color : color string, or array of floats Edge color. Can be a single color format string (default='r'), or a sequence of colors with the same length as edgelist. If numeric values are specified they will be mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters.