Example #1
0
    def visualize(self):
        """Visualize graph like tree"""

        tree = nx.bfs_tree(self.__graph, self.__root)
        plt.figure(figsize=(8, 8))
        pos = eon.hierarchy_pos(tree, self.__root)
        nx.draw(self.__graph, pos=pos, with_labels=True, arrows=True)
        plt.show()
Example #2
0
def plot_cluster_hierarchy(sg,
                           clusts,
                           color_values=None,
                           force_ints_as_cats: bool = True,
                           width: float = 2,
                           lvr_factor: float = 0.5,
                           vert_gap: float = 0.2,
                           min_node_size: float = 10,
                           node_size_multiplier: float = 1e4,
                           node_power: float = 1,
                           root_size: float = 100,
                           non_leaf_size: float = 10,
                           show_labels: bool = False,
                           fontsize=10,
                           root_color: str = '#C0C0C0',
                           non_leaf_color: str = 'k',
                           cmap: str = None,
                           color_key: bool = None,
                           edgecolors: str = 'k',
                           edgewidth: float = 1,
                           alpha: float = 0.7,
                           figsize=(5, 5),
                           ax=None,
                           show_fig: bool = True,
                           savename: str = None,
                           save_dpi=300):
    import networkx as nx
    import EoN
    import math
    from matplotlib.colors import to_hex

    if color_values is None:
        color_values = pd.Series(clusts)
        using_clust_for_colors = True
    else:
        color_values = pd.Series(color_values)
        using_clust_for_colors = False
    color_values = _scatter_fix_type(color_values, force_ints_as_cats)
    cmap, color_key = _scatter_make_colors(
        color_values, cmap, color_key, 'k',
        'longdummyvaluesofh3489hfpiqehdcbla')
    pos = EoN.hierarchy_pos(sg,
                            width=width * math.pi,
                            leaf_vs_root_factor=lvr_factor,
                            vert_gap=vert_gap)
    new_pos = {
        u: (r * math.cos(theta), r * math.sin(theta))
        for u, (theta, r) in pos.items()
    }

    if color_key is None:
        cluster_values = pd.DataFrame({
            'clusters': clusts,
            'v': color_values
        }).groupby('clusters').mean()['v']
        mmv: pd.Series = (cluster_values - cluster_values.min()) / (
            cluster_values.max() - cluster_values.min())
        color_key = {k: to_hex(cmap(v)) for k, v in mmv.to_dict().items()}
    else:
        cluster_values = None

    cs = pd.Series(clusts).value_counts()
    cs = (node_size_multiplier * ((cs / cs.sum())**node_power)).to_dict()
    nc, ns = [], []

    for i in sg.nodes():
        if 'partition_id' in sg.nodes[i]:
            clust_id = sg.nodes[i]['partition_id']
            if cluster_values is not None or using_clust_for_colors:
                nc.append(color_key[clust_id])
                ns.append(max(cs[clust_id], min_node_size))
            else:
                nc.append('white')
                ns.append(0)
        else:
            if sg.nodes[i]['nleaves'] == len(clusts):
                nc.append(root_color)
                ns.append(root_size)
            else:
                nc.append(non_leaf_color)
                ns.append(non_leaf_size)
    if ax is None:
        fig, ax = plt.subplots(1, 1, figsize=figsize)
    nx.draw(sg,
            pos=new_pos,
            node_size=ns,
            node_color=nc,
            ax=ax,
            edgecolors=edgecolors,
            alpha=alpha,
            linewidths=edgewidth)

    if cluster_values is None and using_clust_for_colors is False:
        for i in sg.nodes():
            if 'partition_id' in sg.nodes[i]:
                clust_id = sg.nodes[i]['partition_id']
                idx = clusts == clust_id
                counts = color_values[idx].value_counts()
                _draw_pie(ax, counts.values,
                          [color_key[x] for x in counts.index], new_pos[i][0],
                          new_pos[i][1], max(cs[clust_id], min_node_size))

    if show_labels:
        for i in sg.nodes():
            if 'partition_id' in sg.nodes[i]:
                clust_id = sg.nodes[i]['partition_id']
                ax.text(new_pos[i][0],
                        new_pos[i][1],
                        clust_id,
                        fontsize=fontsize,
                        ha='center',
                        va='center')
    if savename:
        plt.savefig(savename, dpi=save_dpi)
    if show_fig:
        plt.show()
    else:
        return ax
Example #3
0
                 random.choice([True, False]), person[0]])
            person_count += 1
            virus[i].append(
                [person_count,
                 random.choice([True, False]), person[0]])
            person_count += 1

# Prints state of virus after the generations are created.
#print(virus)

# Create graph using networkx
tree = nx.Graph()

# Loop over virus array
for i in virus:
    # Loop over each person in each generation of the virus.
    for person in i:
        # Print that person data
        print(person)
        # Used to ignore the first people in the virus that has no parent as they are the original creator.
        if (person[0] != 1):
            tree.add_edge(person[0], person[2])

# Used to create the hierarchy layout.
pos = EoN.hierarchy_pos(tree, 1)
# Draws the graph using the hierarchy layout and with labels on the nods.
nx.draw(tree, pos=pos, with_labels=True)
# Saves the graph to hierarchy.png
plt.savefig('hierarchy.png', dpi=250)
# Shows the graph once the python script has completed.
plt.show()