NOTEBOOK BASED ON PLOT.LY EXAMPLES


In [11]:
!conda config --add channels conda-forge
!conda install -y 'icu=58.*'


Warning: 'conda-forge' already in 'channels' list, moving to the top
Fetching package metadata ...........
Solving package specifications: ..........

# All requested packages already installed.
# packages in environment at /opt/conda:
#
icu                       58.1                          1    conda-forge

In [5]:
!conda install -y python-igraph networkx plotly


Fetching package metadata ...........
Solving package specifications: ..........

Package plan for installation in environment /opt/conda:

The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    pycairo-1.13.3             |           py35_0         145 KB  conda-forge
    python-igraph-0.7.1.post6  |           py35_4         768 KB  conda-forge
    ------------------------------------------------------------
                                           Total:         913 KB

The following NEW packages will be INSTALLED:

    pycairo:       1.13.3-py35_0      conda-forge
    python-igraph: 0.7.1.post6-py35_4 conda-forge

Fetching packages ...
pycairo-1.13.3 100% |################################| Time: 0:00:01 130.60 kB/s
python-igraph- 100% |################################| Time: 0:00:05 142.71 kB/s
Extracting packages ...
[      COMPLETE      ]|###################################################| 100%
Linking packages ...
[      COMPLETE      ]|###################################################| 100%

In [1]:
import plotly
plotly.__version__


Out[1]:
'2.0.11'

In [2]:
import plotly
from plotly.graph_objs import Scatter, Layout

plotly.offline.plot({
    "data": [Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1])],
    "layout": Layout(title="hello world")
})


Out[2]:
'file:///home/jovyan/work/notebooks/temp-plot.html'

In [12]:
from igraph import *

In [15]:
import urllib.request
import shutil
...
# Download the file from `url` and save it locally under `file_name`:
with urllib.request.urlopen('http://networkdata.ics.uci.edu/data/netscience/netscience.gml') as response, open('netscience.gml.txt', 'wb') as out_file:
    shutil.copyfileobj(response, out_file)

In [16]:
import igraph as ig

G=ig.Graph.Read_GML('netscience.gml.txt')
labels=list(G.vs['label'])
N=len(labels)
E=[e.tuple for e in G.es]# list of edges
layt=G.layout('kk') #kamada-kawai layout
type(layt)


Out[16]:
igraph.layout.Layout

In [20]:
import plotly
help(plotly.offline.iplot)


Help on function iplot in module plotly.offline.offline:

iplot(figure_or_data, show_link=True, link_text='Export to plot.ly', validate=True, image=None, filename='plot_image', image_width=800, image_height=600, config=None)
    Draw plotly graphs inside an IPython or Jupyter notebook without
    connecting to an external server.
    To save the chart to Plotly Cloud or Plotly Enterprise, use
    `plotly.plotly.iplot`.
    To embed an image of the chart, use `plotly.image.ishow`.
    
    figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or
                      dict or list that describes a Plotly graph.
                      See https://plot.ly/python/ for examples of
                      graph descriptions.
    
    Keyword arguments:
    show_link (default=True) -- display a link in the bottom-right corner of
                                of the chart that will export the chart to
                                Plotly Cloud or Plotly Enterprise
    link_text (default='Export to plot.ly') -- the text of export link
    validate (default=True) -- validate that all of the keys in the figure
                               are valid? omit if your version of plotly.js
                               has become outdated with your version of
                               graph_reference.json or if you need to include
                               extra, unnecessary keys in your figure.
    image (default=None |'png' |'jpeg' |'svg' |'webp') -- This parameter sets
        the format of the image to be downloaded, if we choose to download an
        image. This parameter has a default value of None indicating that no
        image should be downloaded. Please note: for higher resolution images
        and more export options, consider making requests to our image servers.
        Type: `help(py.image)` for more details.
    filename (default='plot') -- Sets the name of the file your image
        will be saved to. The extension should not be included.
    image_height (default=600) -- Specifies the height of the image in `px`.
    image_width (default=800) -- Specifies the width of the image in `px`.
    config (default=None) -- Plot view options dictionary. Keyword arguments
        `show_link` and `link_text` set the associated options in this
        dictionary if it doesn't contain them already.
    
    Example:
    ```
    from plotly.offline import init_notebook_mode, iplot
    init_notebook_mode()
    iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}])
    # We can also download an image of the plot by setting the image to the
    format you want. e.g. `image='png'`
    iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}], image='png')
    ```


In [21]:
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode()
iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}])



In [22]:
import plotly.plotly as py
from plotly.graph_objs import *

Xn=[layt[k][0] for k in range(N)]
Yn=[layt[k][1] for k in range(N)]
Xe=[]
Ye=[]
for e in E:
    Xe+=[layt[e[0]][0],layt[e[1]][0], None]
    Ye+=[layt[e[0]][1],layt[e[1]][1], None] 
    
trace1=Scatter(x=Xe,
               y=Ye,
               mode='lines',
               line=Line(color='rgb(210,210,210)', width=1),
               hoverinfo='none'
               )
trace2=Scatter(x=Xn,
               y=Yn,
               mode='markers',
               name='ntw',
               marker=Marker(symbol='dot',
                             size=5, 
                             color='#6959CD',
                             line=Line(color='rgb(50,50,50)', width=0.5)
                             ),
               text=labels,
               hoverinfo='text'
               )

axis=dict(showline=False, # hide axis line, grid, ticklabels and  title
          zeroline=False,
          showgrid=False,
          showticklabels=False,
          title='' 
          )

width=800
height=800
layout=Layout(title= "Coauthorship network of scientists working on network theory and experiment"+\
              "<br> Data source: <a href='https://networkdata.ics.uci.edu/data.php?id=11'> [1]</a>",  
    font= Font(size=12),
    showlegend=False,
    autosize=False,
    width=width,
    height=height,
    xaxis=XAxis(axis),
    yaxis=YAxis(axis),          
    margin=Margin(
        l=40,
        r=40,
        b=85,
        t=100,
    ),
    hovermode='closest',
    annotations=Annotations([
           Annotation(
           showarrow=False, 
            text='This igraph.Graph has the Kamada-Kawai layout',  
            xref='paper',     
            yref='paper',     
            x=0,  
            y=-0.1,  
            xanchor='left',   
            yanchor='bottom',  
            font=Font(
            size=14 
            )     
            )
        ]),           
    )

data=Data([trace1, trace2])
fig=Figure(data=data, layout=layout)
iplot(fig, filename='Coautorship-network-igraph')



In [23]:
import networkx as nx

V=range(N)# list of vertices
g=nx.Graph()
g.add_nodes_from(V)
g.add_edges_from(E)# E is the list of edges

pos=nx.fruchterman_reingold_layout(g)

In [24]:
Xv=[pos[k][0] for k in range(N)]
Yv=[pos[k][1] for k in range(N)]
Xed=[]
Yed=[]
for edge in E:
    Xed+=[pos[edge[0]][0],pos[edge[1]][0], None]
    Yed+=[pos[edge[0]][1],pos[edge[1]][1], None] 
    
trace3=Scatter(x=Xed,
               y=Yed,
               mode='lines',
               line=Line(color='rgb(210,210,210)', width=1),
               hoverinfo='none'
               )
trace4=Scatter(x=Xv,
               y=Yv,
               mode='markers',
               name='net',
               marker=Marker(symbol='dot',
                             size=5, 
                             color='#6959CD',
                             line=Line(color='rgb(50,50,50)', width=0.5)
                             ),
               text=labels,
               hoverinfo='text'
               )

annot="This networkx.Graph has the Fruchterman-Reingold layout<br>Code:"+\
"<a href='http://nbviewer.ipython.org/gist/empet/07ea33b2e4e0b84193bd'> [2]</a>"

data1=Data([trace3, trace4])
fig1=Figure(data=data1, layout=layout)
fig1['layout']['annotations'][0]['text']=annot
iplot(fig1, filename='Coautorship-network-nx')



In [ ]: