我正在尝试使用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()
我非常感谢您的任何建议/反馈。
答案 0 :(得分:2)
让我们使用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(浮点数)–边缘颜色图的最小值和最大值 缩放(默认=无)
edge_color:颜色字符串或浮点型Edge颜色的数组。可以是 单一颜色格式字符串(默认值='r')或一系列颜色 与边列表的长度相同。如果指定了数值 它们将使用edge_cmap和 edge_vmin,edge_vmax参数。