Assocaition Rules Visualization in Python

Viewed 856

I'm trying to visualize the association rules generated by Apriori algorithm. I have 68 rules and tried the code below to visualize the nodes of antecedents and consequent using networkx library. I want to show Rules node in yellow and antecedents and consequents nodes in green:

def draw_graph(rules, rules_to_show):
import networkx as nx  
G1 = nx.DiGraph()

color_map = []
N = 50
colors = np.random.rand(N)
strs = ['R0', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'R7', 'R8', 'R9', 'R10']

for i in range(rules_to_show):
    G1.add_nodes_from(["R"+str(i)])
    
    for a in rules.iloc[i]['antecedents']:
        G1.add_nodes_from([a])
        G1.add_edge(a, "R"+str(i), color = colors[i], weight = 2)
        
    for c in rules.iloc[i]['consequents']:
        G1.add_nodes_from([c])
        G1.add_edge("R"+str(i), c, color = colors[i], weight = 2)
        
for node in G1:
    found_a_string = False
    for item in strs:
        if node == item:
            found_a_string = True
        if found_a_string:
            color_map.append('yellow')
        else:
            color_map.append('green')
            
edges = G1.edges()
colors = [G1[u][v]['color'] for u,v in edges]
weights = [G1[u][v]['weight'] for u,v in edges]

pos = nx.spring_layout(G1, k = 16, scale = 1)
nx.draw_networkx(G1, pos, edgelist=edges, node_color = color_map, edge_color=colors, width=weights, font_size=16, with_labels=False)

for p in pos:
    pos[p][1] += 0.07
nx.draw_networkx_labels(G1, pos)
plt.show()

draw_graph(rules, 10)

I extracted 10 rules from the generated rules but there are still some errors in function nx.draw_networkx which I need help to fix it. The error occurs because of argument node_color = color_map that tries to differentiate rules nodes and other nodes.

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-97-78c7aecc83fc> in <module>
----> 1 draw_graph(rules, 10)

<ipython-input-96-2b661601966f> in draw_graph(rules, rules_to_show)
     34 
     35     pos = nx.spring_layout(G1, k = 16, scale = 1)
---> 36     nx.draw_networkx(G1, pos, edgelist=edges, node_color = color_map, edge_color=colors, width=weights, font_size=16, with_labels=False)
     37 
     38     for p in pos:

~\AppData\Local\Continuum\anaconda3\lib\site-packages\networkx\drawing\nx_pylab.py in draw_networkx(G, pos, arrows, with_labels, **kwds)
    333         pos = nx.drawing.spring_layout(G)  # default to spring layout
    334 
--> 335     draw_networkx_nodes(G, pos, **node_kwds)
    336     draw_networkx_edges(G, pos, arrows=arrows, **edge_kwds)
    337     if with_labels:

~\AppData\Local\Continuum\anaconda3\lib\site-packages\networkx\drawing\nx_pylab.py in draw_networkx_nodes(G, pos, nodelist, node_size, node_color, node_shape, alpha, cmap, vmin, vmax, ax, linewidths, edgecolors, label)
    476         linewidths=linewidths,
    477         edgecolors=edgecolors,
--> 478         label=label,
    479     )
    480     ax.tick_params(

~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
   1436     def inner(ax, *args, data=None, **kwargs):
   1437         if data is None:
-> 1438             return func(ax, *map(sanitize_sequence, args), **kwargs)
   1439 
   1440         bound = new_sig.bind(ax, *args, **kwargs)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\cbook\deprecation.py in wrapper(*inner_args, **inner_kwargs)
    409                          else deprecation_addendum,
    410                 **kwargs)
--> 411         return func(*inner_args, **inner_kwargs)
    412 
    413     return wrapper

~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\axes\_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, plotnonfinite, **kwargs)
   4451             self._parse_scatter_color_args(
   4452                 c, edgecolors, kwargs, x.size,
-> 4453                 get_next_color_func=self._get_patches_for_fill.get_next_color)
   4454 
   4455         if plotnonfinite and colors is None:

~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\axes\_axes.py in _parse_scatter_color_args(c, edgecolors, kwargs, xsize, get_next_color_func)
   4305                     # NB: remember that a single color is also acceptable.
   4306                     # Besides *colors* will be an empty array if c == 'none'.
-> 4307                     raise invalid_shape_exception(len(colors), xsize)
   4308         else:
   4309             colors = None  # use cmap, norm after collection is created

ValueError: 'c' argument has 154 elements, which is inconsistent with 'x' and 'y' with size 14.

I appreciate any help.

0 Answers
Related