I have a dataframe of three classes (0, 1, and 2). After that, I calculate the cooccurrence of the class. Further, the diagonal element is assigned to 0. In conclusion, try to plot a cooccurrence graph with the width of each edge which denotes the strength or frequency of cooccurrence # Python code demonstrate how to create # Pandas DataFrame by lists of dicts. import pandas as pd import numpy as np
# Initialize data to lists.
data = [{'0': 1, '1': 0, '2': 1},
{'0': 1, '1': 0, '2': 1},
{'0': 1, '1': 1, '2': 0},
{'0': 1, '1': 0, '2': 1},
{'0': 1, '1': 1, '2': 0},
{'0': 0, '1': 0, '2': 1},
{'0': 1, '1': 0, '2': 1},
{'0': 0, '1': 0, '2': 0},
{'0': 1, '1': 1, '2': 1},
{'0': 0, '1': 1, '2': 0},
{'0': 1, '1': 0, '2': 1},
{'0': 0, '1': 1, '2': 0},
{'0': 1, '1': 0, '2': 0},
{'0': 0, '1': 1, '2': 1}]
# Creates DataFrame.
df = pd.DataFrame(data)
# Print the data
df
#Find Co-occurence
df_asint = df.astype(int)
coocc = df_asint.T.dot(df_asint)
coocc
#Assign diagonal=0
np.fill_diagonal(coocc.values,0)
coocc
#plot the graph
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib
A=np.matrix(coocc)
G=nx.from_numpy_matrix(A)
#fig = plt.figure(1, figsize=(10, 80), dpi=30)
f = plt.figure()
plt.axis('off')
nx.draw_networkx(nx.from_pandas_adjacency(coocc),ax=f.add_subplot(111),node_color=["cyan",
"Red","yellow"],node_size=350)
now I would like to plot the width of each edge which denotes the strength or frequency of cooccurrence
CodePudding user response:
The only substantial thing you needed to add was creating a list of weights
and passing it to the nx.draw_networkx
function as width=weights
.
Below is the updated code:
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib as mpl
# Initialize data to lists.
data = [{'0': 1, '1': 0, '2': 1},
{'0': 1, '1': 0, '2': 1},
{'0': 1, '1': 1, '2': 0},
{'0': 1, '1': 0, '2': 1},
{'0': 1, '1': 1, '2': 0},
{'0': 0, '1': 0, '2': 1},
{'0': 1, '1': 0, '2': 1},
{'0': 0, '1': 0, '2': 0},
{'0': 1, '1': 1, '2': 1},
{'0': 0, '1': 1, '2': 0},
{'0': 1, '1': 0, '2': 1},
{'0': 0, '1': 1, '2': 0},
{'0': 1, '1': 0, '2': 0},
{'0': 0, '1': 1, '2': 1}]
# Creates DataFrame.
df = pd.DataFrame(data)
# Print the data
df
#Find Co-occurence
df_asint = df.astype(int)
coocc = df_asint.T.dot(df_asint)
coocc
#Assign diagonal=0
np.fill_diagonal(coocc.values,0)
coocc
#plot the graph
A=np.matrix(coocc)
G=nx.from_numpy_matrix(A)
# store the weights in a list
weights = [G[u][v]['weight'] for u,v in G.edges()]
# initialize the figure
fig, ax = plt.subplots()
# draw the graph with edge size given by the weight
nx.draw_networkx(G, ax=ax, width=weights, node_color=["cyan", "Red","yellow"], node_size=350)
# remove the axis
plt.axis('off')