Skip to content

Instantly share code, notes, and snippets.

@JamesPHoughton
Last active June 26, 2024 21:33
Show Gist options
  • Save JamesPHoughton/55be4a6d30fe56ae163ada176c5c7553 to your computer and use it in GitHub Desktop.
Save JamesPHoughton/55be4a6d30fe56ae163ada176c5c7553 to your computer and use it in GitHub Desktop.
How to create rotary labels in networkx circular layout
g = nx.complete_graph([
    "playground equipment", "evanescent champagne", "curved spacetime", 
    "magic flute", "market returns", "spotty memory",
    "languid feeling", "include numpy as np", "acidic chemical", 
    "downton abbey", "tumble weeds", "precede the cause"])
node_locs = nx.circular_layout(g)
theta = {k: np.arctan2(v[1], v[0]) * 180/np.pi for k, v in node_locs.items() }


plt.figure(figsize=(8,8))
nx.draw_networkx_nodes(g, pos=node_locs, alpha=.5)
labels = nx.draw_networkx_labels(g, pos=node_locs, font_size=12, ha='left')

for key,t in labels.items():
    if 90 < theta[key] or theta[key] < -90 :
        angle = 180 + theta[key]
        t.set_ha('right')
    else:
        angle = theta[key]
        t.set_ha('left')
    t.set_va('center')
    t.set_rotation(angle)
    t.set_rotation_mode('anchor')

nx.draw_networkx_edges(g, pos=node_locs, alpha=.4)
plt.box("off")
plt.xlim(-2,2)
plt.ylim(-2,2)

Gives: image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment