[networkx] Визуализируйте некоторые точки на графике, точки перемещаются по ссылке, но они не являются узлами - PullRequest
0 голосов
/ 22 мая 2018

Я хочу визуализировать некоторые точки на графике, точки перемещаются по ссылке, но они не являются узлами.В настоящее время я добавил некоторые точки расположения, но не могу отобразить их на рисунке.

Это код # - - кодирование: utf-8 - -

import networkx as nx
import matplotlib.pyplot as plt
import itertools
import math

#from mesa.space import NetworkGrid
#from mesa import Agent, Model
#from mesa.time import RandomActivation
#from mesa.datacollection import DataCollector
#from mesa.space import NetworkGrid
#%%Build a graph
G=nx.Graph()
G.add_node("GPs")
G.add_node("AcuteCares")
G.add_node("Waitlists")
G.add_node("newPatients")
G.add_node("Preventabledeaths")
G.add_node("ReviewPatients")
G.add_node("DeathPools")
G.add_node("DNAPool1s")
G.add_node("DNAPool2s")
G.add_node("UntreatedPopulations")
G.add_node("SAPops")



labeldict = {}
labeldict["GPs"] = "GP"
labeldict["AcuteCares"] = "Acute Care"
labeldict["Waitlists"] = "Waitlist"
labeldict["newPatients"] = "New Patients"
labeldict["Preventabledeaths"] = "Preventable Deaths"
labeldict["ReviewPatients"] = "Review Patients"
labeldict["DeathPools"] = "Natural Deaths"
labeldict["DNAPool1s"] = "First DNA"
labeldict["DNAPool2s"] = "Second DNA"
labeldict["UntreatedPopulations"] = "Untreated Population"
labeldict["SAPops"] = "General Population"

G.node["Preventabledeaths"]['pos']=(0,6)
G.node["ReviewPatients"]['pos']=(-3,5)
G.node["UntreatedPopulations"]['pos']=(3,5)
G.node["DNAPool2s"]['pos']=(-3,3)
G.node["Waitlists"]['pos']=(3,3)
G.node["AcuteCares"]['pos']=(-5,0)
G.node["DNAPool1s"]['pos']=(5,0)
G.node["GPs"]['pos']=(-3,-5)
G.node["DeathPools"]['pos']=(3,-5)
G.node["SAPops"]['pos']=(-3,-3)
G.node["newPatients"]['pos']=(3,-3)

edges=itertools.permutations(G.nodes(),2)
G.add_edges_from(edges)

pos=nx.get_node_attributes(G,'pos')
nx.draw(G,pos,labels=labeldict, with_labels = True)
plt.show()
#grid = NetworkGrid(G)

# %%    
def arclen(edge):
    """
    calculate the length of an edge. The format of edge is like: ('UntreatedPopulations', 'SAPops')
    """
    dist_edge = math.sqrt((G.node[edge[0]]['pos'][0] - G.node[edge[1]]['pos'][0])**2 + (G.node[edge[0]]['pos'][1] - G.node[edge[1]]['pos'][1])**2)
    return dist_edge

def patientcor(speed,step,edge):
    """get the coordinate of point along the edge, speed is the moving speed per step,
    time is the number of steps, edge is the specific edge
    """
    x=G.node[edge[0]]['pos'][0] + speed*step/arclen(edge) *(G.node[edge[1]]['pos'][0] -G.node[edge[0]]['pos'][0])
    y=G.node[edge[0]]['pos'][1] + speed*step/arclen(edge) *(G.node[edge[1]]['pos'][1] -G.node[edge[0]]['pos'][1])
    return (x,y)
#%% Visualise the graph, set the speed at 0.2, time is 0,1,2
edge=("SAPops","GPs")
for t in range(3):
    pos[t]=patientcor(0.2, t,edge) #add the location of point on the link per step to the dict
    nx.draw(G,pos, labels=labeldict,with_labels = True) #visualise pos dict along with the graph, but the additional points other than nodes do not appear on the figure
    plt.show()

На графике показаны только узлы, но не точки, которые движутся по краям:

image

1 Ответ

0 голосов
/ 22 мая 2018

Команда nx.draw построит только те узлы, которые находятся на графике.Если в вашем словаре pos указаны местоположения других точек, он будет игнорировать их.Я считаю, что это правильное поведение, и я могу подумать, что мое кодирование было бы намного сложнее, если бы оно также отображало другие точки, которые появились в моем словаре pos.

Для того, что вы хотите,просто создайте новый список точек, которые вы хотите построить (или в вашем примере это выглядит как единственная точка).Затем используйте команду scatter команды matplotlib.

#stuff skipped here

edge=("SAPops","GPs")
for t in range(3):
    mypoint = patientcor(0.2, t,edge) 
    nx.draw(G,pos, labels=labeldict,with_labels = True) #visualise pos dict along with the graph, but the additional points other than nodes do not appear on the figure
    plt.scatter([mypoint[0]], [mypoint[1]])
    plt.show()

sample image

Возможно, вы захотите поиграть с размерами узлов иконкретные места этих точек.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...