Skip to content

Instantly share code, notes, and snippets.

@creotiv
Created October 19, 2018 19:02
Show Gist options
  • Save creotiv/b9c51cdb56ad56ea2caf015cadd57606 to your computer and use it in GitHub Desktop.
Save creotiv/b9c51cdb56ad56ea2caf015cadd57606 to your computer and use it in GitHub Desktop.
Plot NetworkX graph with Plotly in Google Colab
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot, plot
init_notebook_mode(connected=True)
def configure_plotly_browser_state():
import IPython
display(IPython.core.display.HTML('''
<script src="/static/components/requirejs/require.js"></script>
<script>
requirejs.config({
paths: {
base: '/static/base',
plotly: 'https://cdn.plot.ly/plotly-latest.min.js?noext',
},
});
</script>
'''))
import IPython
IPython.get_ipython().events.register('pre_run_cell', configure_plotly_browser_state)
class MyGraph(nx.Graph):
def add_relation(self, node_from, node_to):
self.add_node(node_from)
self.add_node(node_to)
self.add_edge(node_from, node_to)
def plot(self):
# Nodes
pos=nx.fruchterman_reingold_layout(self)
Xn=[pos[k][0] for k in pos.keys()]
Yn=[pos[k][1] for k in pos.keys()]
trace_nodes=dict(type='scatter',
x=Xn,
y=Yn,
mode='markers',
marker=dict(size=28, color='#007FFF'),
text=list(pos.keys()),
hoverinfo='text')
# Edges
Xe=[]
Ye=[]
for e in G.edges():
Xe.extend([pos[e[0]][0], pos[e[1]][0], None])
Ye.extend([pos[e[0]][1], pos[e[1]][1], None])
trace_edges=dict(type='scatter',
mode='lines',
x=Xe,
y=Ye,
line=dict(width=1, color='#555555'),
hoverinfo='none'
)
axis=dict(showline=False, # hide axis line, grid, ticklabels and title
zeroline=False,
showgrid=False,
showticklabels=False,
title=''
)
layout=dict(title= 'My Graph',
font= dict(family='Balto'),
width=600,
height=600,
autosize=False,
showlegend=False,
xaxis=axis,
yaxis=axis,
margin=dict(
l=40,
r=40,
b=85,
t=100,
pad=0,
),
hovermode='closest',
plot_bgcolor='#ffffff', #set background color
)
fig = dict(data=[trace_edges, trace_nodes], layout=layout)
iplot(fig)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment