Skip to content

Instantly share code, notes, and snippets.

@DMTSource
Last active June 1, 2021 15:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DMTSource/878502b94308c1e5ac6d6851a225f0c9 to your computer and use it in GitHub Desktop.
Save DMTSource/878502b94308c1e5ac6d6851a225f0c9 to your computer and use it in GitHub Desktop.
Deap Pretty Node Plot Example Code Example (Need to bring your own deap Individuals in)
# Derek M. Tishler
# nx plot example deap individual
# For post: https://groups.google.com/g/deap-users/c/nZFZpm5OPZA
import matplotlib.pyplot as plt
import networkx as nx
from networkx.drawing.nx_agraph import graphviz_layout
## May need is resuming session
#from deap import creator
#creator.create("Individual", gp.PrimitiveTree, fitness=creator.FitnessMin)
def plot_individual_tree(individual):
fig = plt.figure(figsize=(26,11), dpi=150)
ax1 = plt.subplot2grid((1,1), (0,0), rowspan=1, colspan=1)
nodes, edges, labels = gp.graph(individual)
g = nx.Graph()
g.add_nodes_from(nodes)
g.add_edges_from(edges)
pos = graphviz_layout(g, prog="dot")
node_colors = []
for prim in individual:
if len([prim.name for flag in ['PL'] if flag in prim.name]) > 0 :
node_colors.append('peachpuff')
elif len([prim.name for flag in ['RL'] if flag in prim.name]) > 0 :
node_colors.append('lightgreen')
elif len([prim.name for flag in ['CL'] if flag in prim.name]) > 0 :
node_colors.append('tomato')
# Draw network, but with custo node size and above labels
nx.draw_networkx_nodes(g, pos, ax=ax1,node_size=3200, node_color=node_colors)#, node_color=range(len(nodes)), cmap=plt.cm.Blues)
nx.draw_networkx_edges(g, pos, ax=ax1)
# adjust labels, replalce 'ws' with new line+ws for easier fit in circle for long names
labels = {key: str(val).replace('ws','\nws') for key, val in labels.items()}
nx.draw_networkx_labels(g, pos, labels, ax=ax1, font_size=10)
ax1.set_axis_off()
plt.tight_layout()
plt.savefig('individual.png')
plt.clf()
plt.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment