Skip to content

Instantly share code, notes, and snippets.

View jinhangjiang's full-sized avatar

Jinhang Jiang jinhangjiang

  • McKesson
View GitHub Profile
@jinhangjiang
jinhangjiang / convert_graph.py
Last active June 6, 2021 03:37
Convert an edge list to a NetworkX graph
import networkx as nx
# "edgelist" will be prepared with 3 columns: Source, Target, and Weights
# "name" give your graph a name since we are going to do graphs comparison
def convert_graph(edgelist,name):
graph=nx.Graph() # this only helps you generate a undirected graph
graph.add_weighted_edges_from([tuple(x) for x in edgelist.values]) # add weights to the edges
graph.name = "Network Graph for" + " " + name # name the graph
print(nx.info(graph)) # this will give you the basic info about the graph
print("------------------------------------")
@jinhangjiang
jinhangjiang / drawgraph.py
Created June 6, 2021 03:46
NetworkX Draw Graphs
def drawgraph(graph, density=False):
## insert the graph you just converted from the edge list
## the default for the density is False. If density = True, it will return the density of the graph
edges,weights = zip(*nx.get_edge_attributes(graph,'weight').items()) ## extract the edges and weights for later use
## k will affect the optimal distance between nodes.
## more types of layouts can be found at https://networkx.org/documentation/stable/reference/drawing.html
pos=nx.spring_layout(graph,k=0.05,seed=42)
nx.draw_networkx(graph,
pos,
with_labels=True,
@jinhangjiang
jinhangjiang / drawnodegraph.py
Created June 6, 2021 04:01
Draw subgraphs for a certain node and set a bar of weights to reduce complexity
def drawnodegraph(graph, nodename, info=False,weightbar=0):
# graph will be your networkx graph
# nodename will be the node that you want to focus on
# the default value for weightbar is 0, if increase the bar, rare relationship will be removed. Assuming no negative weights
temp = graph.copy(as_view=False) # make a temporary graph to avoid losing original ones
temp.remove_edges_from((e for e, w in nx.get_edge_attributes(temp,'weight').items() if w <= weightbar)) # remove rare relationhsip if weightbar is not 0
nodelist = list(temp.neighbors(n=nodename)) #generate the nodes that have relationship with our target node
nodelist.append(nodename) # add the target to the list
Sub = temp.subgraph(nodelist) # draw subgraph
edges,weights = zip(*nx.get_edge_attributes(Sub,'weight').items())
@jinhangjiang
jinhangjiang / creategraphs.R
Last active June 24, 2021 08:16
igraph graph.formula
## Create undirected graphs
g <- graph_from_literal(1-2, 1-3, 1-7, 3-4, 2-3, 2-4, 3-5, 4-5, 4-6, 4-7, 5-6, 5-8, 6-7, 7-8)
## Create directed graphs using addition or substraction operators
dg <- graph_from_literal(JFK-+PEK, JFK-+CDG, PEK++CDG)
@jinhangjiang
jinhangjiang / getbasicinfo.R
Last active June 24, 2021 08:20
igraph manipulate graphs
## check out the vertices and the order
V(g)
#output:
# + 7/7 vertices, named, from bd40644:
# [1] 1 2 3 4 5 6 7 8
vcount(g)
# [1] 8
## check out the edges and the size
@jinhangjiang
jinhangjiang / representationsofgraph.R
Created June 24, 2021 09:04
igraph label vertices
## Adjacency list
adjlist <- get.adjlist(g)
adjlist[1]
# $Adam
# + 3/8 vertices, named, from 50df64b:
# [1] Judy Bobby Sam
## Edge list
as.data.frame(get.edgelist(g))
# V1 V2
## remove specific nodes/vertices
h1 <- g - vertices(c("Adam","Judy"))
## generate subgraph by manual input
h2 <- graph_from_literal("Adam"-"Judy", "Adam"-"Bobby", "Adam"-"Sam", "Judy"-"Bobby","Judy"-"Frank")
## join graphs
h3 <- union(h1,h2)
# or, h3 <- h1 + h2
@jinhangjiang
jinhangjiang / readdataigraph.R
Created June 24, 2021 09:59
read data using igraph
library(sand)
g.lazega <- graph_from_data_frame(elist.lazega,
directed="FALSE",
vertices=v.attr.lazega)
vertex_attr_names(g.lazega)
# [1] "name" "Seniority" "Status" "Gender" "Office"
# [6] "Years" "Age" "Practice" "School"
plot(g.lazega)
@jinhangjiang
jinhangjiang / 3DScatterGraph-1.py
Last active June 25, 2021 09:35
Visualize High-Dimensional Network Data with 3D Scatter Plot
#!pip install -U node2vec
# load packages
import pandas as pd
import networkx as nx
from node2vec import Node2Vec
from matplotlib import pyplot as plt, rc, cm
from matplotlib.pyplot import figure
import matplotlib.animation as animation
from mpl_toolkits.mplot3d import Axes3D
@jinhangjiang
jinhangjiang / 3DScatterGraph-2.py
Created June 25, 2021 09:44
Visualize High-Dimensional Network Data with 3D Scatter Plot
def ThreeDplot(model):
"Creates TSNE model and plots it"
"Get the labels and vectors from ndoe2vec mode"
labels = []
tokens = []
for word in model.wv.vocab:
tokens.append(model[word])
labels.append(word)