Exemplo n.º 1
0
def compareFileExtViaBoxPlots(dictParam, fileNameParam, extList):
    import plotly.plotly as py
    import plotly.graph_objs as go
    from plotly.graph_objs import Layout, YAxis, Figure, Margin, Font
    #from plotly.graph_objs import Bar, Marker, Data, Layout, XAxis, YAxis, Figure, Margin, Font
    dataToPlot = []
    for it_ in extList:
        trace_ = go.Box(y=dictParam[it_], name=it_)
        dataToPlot.append(trace_)

    layoutToUse = Layout(
        title='Distribution of File Types : ' + fileNameParam,
        titlefont=Font(family='Times New Roman', size=18, color='#000000'),
        yaxis=YAxis(
            showgrid=True,
            showline=True,
            title='Values',
            #range=[0, 35],
            autorange=True,
            titlefont=Font(family='Times New Roman', size=12,
                           color='#000000')),
        width=800,
        height=600,
        margin=Margin(l=140, r=40, b=50, t=80),
    )

    #plot_url = py.plot(dataToPlot, filename=fileNameParam)
    figToPlot = Figure(data=dataToPlot, layout=layoutToUse)
    fileNameParam = "plot-session-info/" + fileNameParam + ".png"
    py.image.save_as(figToPlot, fileNameParam)
Exemplo n.º 2
0
def plotSharpVSOthers(dictParam, fileNameParam, extOfInterest="cSharpCount"):
    import plotly.plotly as py
    import plotly.graph_objs as go
    from plotly.graph_objs import Layout, YAxis, Figure, Margin, Font
    cSharpList = dictParam[extOfInterest]
    otherList = [100.0 - float(x) for x in cSharpList]
    cSharpTrace_ = go.Box(y=cSharpList, name="C# Files")
    otherTrace_ = go.Box(y=otherList, name="Other Files")
    dataToPlot = [cSharpTrace_, otherTrace_]
    layoutToUse = Layout(
        title='Distribution of File Types : ' + fileNameParam,
        titlefont=Font(family='Times New Roman', size=18, color='#000000'),
        yaxis=YAxis(
            showgrid=True,
            showline=True,
            title='Values',
            #range=[0, 35],
            autorange=True,
            titlefont=Font(family='Times New Roman', size=12,
                           color='#000000')),
        width=800,
        height=600,
        margin=Margin(l=140, r=40, b=50, t=80),
    )

    #plot_url = py.plot(dataToPlot, filename=fileNameParam)
    figToPlot = Figure(data=dataToPlot, layout=layoutToUse)
    fileNameParam = "plot-session-info/" + fileNameParam + ".png"
    py.image.save_as(figToPlot, fileNameParam)
Exemplo n.º 3
0
def kamervragen_reply_time_per_year(years, kamervraag_durations):
    fig = ff.create_distplot(
        kamervraag_durations,
        years,
        # colors=colors,
        bin_size=1,
        show_curve=True,
        show_hist=False,
        show_rug=False)

    xaxis = XAxis(range=[0, 60])

    fig['layout'].update(xaxis=xaxis)
    # fig['layout'].update(title="Kamervraag Antwoordtijd per Ministerie tijdens Rutte-II (KDE probability distributie)")
    fig['layout'].update(xaxis=dict(title='Antwoordtijd [dagen]'))
    # fig['layout'].update(yaxis=dict(title=''))
    fig['layout'].update(height=700)
    fig['layout'].update(margin=Margin(t=20))
    legend = dict(
        # x=0.01,
        # y=1,
        bordercolor='#E2E2E2',
        bgcolor='#FFFFFF',
        borderwidth=2)
    fig['layout'].update(legend=legend)

    return Plot.create_plot_html_default(figure_or_data=fig)
Exemplo n.º 4
0
def plotTwoGroups(group1Param, group2Param, yAxisParam, titleParam,
                  fileNameParam):
    import plotly.plotly as py
    import plotly.graph_objs as go
    from plotly.graph_objs import Layout, YAxis, Figure, Margin, Font

    group1Trace_ = go.Box(y=group1Param, name="High Productivity Sessions")
    group2Trace_ = go.Box(y=group2Param, name="Low Productivity Sessions")
    dataToPlot = [group1Trace_, group2Trace_]
    layoutToUse = Layout(
        title='Summary of 84030 Sessions  : ' + titleParam,
        titlefont=Font(family='Times New Roman', size=18, color='#000000'),
        yaxis=YAxis(
            showgrid=True,
            showline=True,
            title=yAxisParam,
            #range=[0, 35],
            autorange=True,
            titlefont=Font(family='Times New Roman', size=12,
                           color='#000000')),
        width=800,
        height=600,
        margin=Margin(l=140, r=40, b=50, t=80),
    )

    figToPlot = Figure(data=dataToPlot, layout=layoutToUse)
    fileNameParam = "plot-session-info/" + fileNameParam + ".png"
    py.image.save_as(figToPlot, fileNameParam)
    return "DONE!"
Exemplo n.º 5
0
def test_to_string():
    fig = Figure(data=Data([
        Scatter(x=[1, 2, 3, 4], y=[10, 15, 13, 17]),
        Scatter(x=[1, 2, 3, 4], y=[16, 5, 11, 9])
    ]),
                 layout=Layout(autosize=False,
                               width=500,
                               height=500,
                               margin=Margin(l=65, r=50, b=65, t=65)))
    fig_string = fig.to_string(pretty=False)
    comp_string = ('Figure(\n'
                   '    data=Data([\n'
                   '        Scatter(\n'
                   '            x=[1, 2, 3, 4],\n'
                   '            y=[10, 15, 13, 17]\n'
                   '        ),\n'
                   '        Scatter(\n'
                   '            x=[1, 2, 3, 4],\n'
                   '            y=[16, 5, 11, 9]\n'
                   '        )\n'
                   '    ]),\n'
                   '    layout=Layout(\n'
                   '        autosize=False,\n'
                   '        width=500,\n'
                   '        height=500,\n'
                   '        margin=Margin(\n'
                   '            l=65,\n'
                   '            r=50,\n'
                   '            b=65,\n'
                   '            t=65\n'
                   '        )\n'
                   '    )\n'
                   ')')
    assert fig_string == comp_string
Exemplo n.º 6
0
def compareViaBoxPlot(posGroupParam, zeroGroupParam, negGroupParam,
                      fileNameParam):
    import plotly.plotly as py
    import plotly.graph_objs as go
    from plotly.graph_objs import Layout, YAxis, Figure, Margin, Font
    #from plotly.graph_objs import Bar, Marker, Data, Layout, XAxis, YAxis, Figure, Margin, Font

    posGroup = go.Box(y=posGroupParam, name='Corr. >= 0.50')
    zeroGroup = go.Box(y=zeroGroupParam, name='Corr. within 0.0 & 0.499')
    negGroup = go.Box(y=negGroupParam, name='Corr. < 0.0')

    layoutToUse = Layout(
        title='Distribution of Three Groups: ' + fileNameParam,
        titlefont=Font(family='Times New Roman', size=18, color='#000000'),
        yaxis=YAxis(
            showgrid=True,
            showline=True,
            title='Values',
            #range=[0, 35],
            autorange=True,
            titlefont=Font(family='Times New Roman', size=12,
                           color='#000000')),
        width=800,
        height=600,
        margin=Margin(l=140, r=40, b=50, t=80),
    )

    dataToPlot = [posGroup, zeroGroup, negGroup]
    #plot_url = py.plot(dataToPlot, filename=fileNameParam)
    figToPlot = Figure(data=dataToPlot, layout=layoutToUse)
    fileNameParam = "plots/" + fileNameParam + ".png"
    py.image.save_as(figToPlot, fileNameParam)
Exemplo n.º 7
0
    def plotConfusionMatrix(self, dataFrame, name):
        """
    @param data         (pandas DF)     The confusion matrix.
    @param name         (str)
    """
        labels = dataFrame.columns.values.tolist()
        values = map(list, dataFrame.values)

        data = Data(
            [Heatmap(z=values, x=labels, y=labels, colorscale='YIGnBu')])

        layout = Layout(
            title='Confusion Matrix for ' + name,
            xaxis=XAxis(title='',
                        side='top',
                        titlefont=Font(family='Courier New, monospace',
                                       size=18,
                                       color='#7f7f7f')),
            yaxis=YAxis(title='',
                        titlefont=Font(family='Courier New, monospace',
                                       size=18,
                                       color='#7f7f7f'),
                        autorange='reversed'),
            barmode='overlay',
            autosize=True,
            width=1000,
            height=1000,
            margin=Margin(l=80, r=80, b=120, t=140))

        fig = Figure(data=data, layout=layout)
        plot_url = py.plot(fig)
        print "Confusion matrix URL: ", plot_url
Exemplo n.º 8
0
def plot_ly(subgraph, title, data, measure, colorscale='Hot'):
    '''
    Function to get a plotly figure object to be plotted
    Args:
        subgraph (NetworkX Graph): the graph to be plotted
        title (str): the title for the plot
        data (dict): the measured data to be plotted
        measure (str): the measure being plotted
        colorscale (str): colorscale for the data measure
        ColorScale options
        'Greys' | 'Greens' | 'Bluered' | 'Hot' | 'Picnic' | 'Portland' |
        Jet' | 'RdBu' | 'Blackbody' | 'Earth' | 'Electric' | 'YIOrRd' |
        'YIGnBu'
    '''
    pos = nx.spring_layout(subgraph, k=.12)
    nodes = list(subgraph.node.keys())
    nodes.sort()
    labels = []
    for node in subgraph.nodes():
        author_name = subgraph.node[node]['data']['author']['name'].title()
        label = "{}<br>{} = {}".format(author_name, measure, str(data[node]))
        labels.append(label)
    trace1 = scatter_edges(subgraph, pos)
    trace2 = scatter_nodes(pos=pos,
                           labels=labels,
                           title=title,
                           data=data,
                           nodes=nodes,
                           colorscale=colorscale)
    width = 800
    height = 600
    axis = dict(showline=False,
                zeroline=False,
                showgrid=False,
                showticklabels=False,
                title='')
    layout = Layout(title=title,
                    font=Font(),
                    showlegend=False,
                    autosize=False,
                    width=width,
                    height=height,
                    xaxis=dict(title='',
                               titlefont=dict(size=14, color='#7f7f7f'),
                               showline=False,
                               showticklabels=False,
                               zeroline=False),
                    yaxis=YAxis(axis),
                    margin=Margin(
                        l=40,
                        r=40,
                        b=85,
                        t=100,
                        pad=0,
                    ),
                    hovermode='closest',
                    plot_bgcolor='#EFECEA')
    data = Data([trace1, trace2])
    fig = Figure(data=data, layout=layout)
    return fig
Exemplo n.º 9
0
def plotDistForThreeGroups(group1, group2, group3, fileNameParam):
    import plotly.plotly as py
    import plotly.graph_objs as go
    from plotly.graph_objs import Layout, YAxis, Figure, Margin, Font
    #from plotly.graph_objs import Bar, Marker, Data, Layout, XAxis, YAxis, Figure, Margin, Font
    dataToPlot = []
    g1Trace_ = go.Box(y=group1, name="Corr >=0.50")
    g2Trace_ = go.Box(y=group2, name="Corr >=0.0 AND Corr <=0.499")
    g3Trace_ = go.Box(y=group3, name="Corr < 0.0")
    dataToPlot = [g1Trace_, g2Trace_, g3Trace_]
    layoutToUse = Layout(
        title='Distribution of : ' + fileNameParam,
        titlefont=Font(family='Times New Roman', size=18, color='#000000'),
        yaxis=YAxis(
            showgrid=True,
            showline=True,
            title='Values',
            #range=[0, 35],
            autorange=True,
            titlefont=Font(family='Times New Roman', size=12,
                           color='#000000')),
        width=800,
        height=600,
        margin=Margin(l=140, r=40, b=50, t=80),
    )

    #plot_url = py.plot(dataToPlot, filename=fileNameParam)
    figToPlot = Figure(data=dataToPlot, layout=layoutToUse)
    fileNameParam = "plot-session-info/" + fileNameParam + ".png"
    py.image.save_as(figToPlot, fileNameParam)
Exemplo n.º 10
0
def compareFileExtViaBarPlots(dictParam, fileNameParam, listParam):
    import plotly.plotly as py
    import plotly.graph_objs as go
    from plotly.graph_objs import Layout, YAxis, Figure, Margin, Font
    import numpy as np
    xList = []
    yList = []
    for it_ in listParam:
        xList.append(it_)
        yList.append(np.mean(dictParam[it_]))

    dataToPlot = [go.Bar(x=xList, y=yList)]
    layoutToUse = Layout(
        title='Distribution of File Types (Average) : ' + fileNameParam,
        titlefont=Font(family='Times New Roman', size=18, color='#000000'),
        yaxis=YAxis(
            showgrid=True,
            showline=True,
            title='Values',
            #range=[0, 35],
            autorange=True,
            titlefont=Font(family='Times New Roman', size=12,
                           color='#000000')),
        width=800,
        height=600,
        margin=Margin(l=140, r=40, b=50, t=80),
    )

    #plot_url = py.plot(dataToPlot, filename=fileNameParam)
    figToPlot = Figure(data=dataToPlot, layout=layoutToUse)
    fileNameParam = "plot-session-info/" + fileNameParam + ".png"
    py.image.save_as(figToPlot, fileNameParam)
Exemplo n.º 11
0
 def create_layout(self):
     return Layout(
         # title="Kamervraag Antwoordtijd vs Tijd",
         xaxis=dict(title='Kamervraag Ingediend [tijd]'),
         yaxis=dict(title='Antwoordtijd [dagen]'),
         autosize=False,
         width=1000,
         height=500,
         margin=Margin(t=20))
Exemplo n.º 12
0
 def setUp(self):
     super(TestToDataframe, self).setUp()
     self.fig = Figure(data=Data([
         Scatter(x=[52698, 43117],
                 y=[53, 31],
                 mode='markers',
                 name='North America',
                 text=['United States', 'Canada'],
                 marker=Marker(color='rgb(164, 194, 244)',
                               size=12,
                               line=Line(color='white', width=0.5))),
         Scatter(x=[
             39317, 37236, 35650, 30066, 29570, 27159, 23557, 21046, 18007
         ],
                 y=[33, 20, 13, 19, 27, 19, 49, 44, 38],
                 mode='markers',
                 name='Europe',
                 text=[
                     'Germany', 'Britain', 'France', 'Spain', 'Italy',
                     'Czech Rep.', 'Greece', 'Poland'
                 ],
                 marker=Marker(color='rgb(255, 217, 102)',
                               size=12,
                               line=Line(color='white', width=0.5))),
         Scatter(x=[42952, 37037, 33106, 17478, 9813, 5253, 4692, 3899],
                 y=[23, 42, 54, 89, 14, 99, 93, 70],
                 mode='markers',
                 name='Asia/Pacific',
                 text=[
                     'Australia', 'Japan', 'South Korea', 'Malaysia',
                     'China', 'Indonesia', 'Philippines', 'India'
                 ],
                 marker=Marker(color='rgb(234, 153, 153)',
                               size=12,
                               line=Line(color='white', width=0.5))),
         Scatter(x=[19097, 18601, 15595, 13546, 12026, 7434, 5419],
                 y=[43, 47, 56, 80, 86, 93, 80],
                 mode='markers',
                 name='Latin America',
                 text=[
                     'Chile', 'Argentina', 'Mexico', 'Venezuela',
                     'Venezuela', 'El Salvador', 'Bolivia'
                 ],
                 marker=Marker(color='rgb(142, 124, 195)',
                               size=12,
                               line=Line(color='white', width=0.5)))
     ]),
                       layout=Layout(title='Quarter 1 Growth',
                                     autosize=False,
                                     width=500,
                                     height=500,
                                     xaxis=XAxis(title='GDP per Capita',
                                                 showgrid=False,
                                                 zeroline=False),
                                     yaxis=YAxis(title='Percent',
                                                 showline=False),
                                     margin=Margin(l=65, r=50, b=65, t=90)))
Exemplo n.º 13
0
 def create_layout(self):
     return Layout(
         yaxis=dict(title='Kamervragen per maand'),
         margin=Margin(t=20, b=30),
         legend=dict(
             # x=0.01,
             # y=1,
             bordercolor='#E2E2E2',
             bgcolor='#FFFFFF',
             borderwidth=2))
Exemplo n.º 14
0
 def create_layout(self):
     return Layout(title=self.plot_title,
                   xaxis=dict(title='Tijd'),
                   yaxis=dict(title='Kamervragen per week'),
                   margin=Margin(t=20),
                   legend=dict(x=0.01,
                               y=1,
                               bordercolor='#E2E2E2',
                               bgcolor='#FFFFFF',
                               borderwidth=2))
Exemplo n.º 15
0
    def compare_runs(self,
                     column,
                     loc=(),
                     iloc=(),
                     subsample=1,
                     marker=False,
                     reference=None,
                     verbose=True) -> None:

        mode = 'lines' if (not marker) else 'lines+markers'
        if isinstance(iloc, int):
            iloc = [i for i in range(iloc)
                    ] if (iloc > 0) else [i for i in range(iloc, 0, 1)]

        data = []

        def _add(entry, name):
            x, y = zip(*entry[column])
            x, y = arr(x)[::subsample], arr(y)[::subsample]

            data.append(Scatter(x=x, y=y, name=name, mode=mode))

        for idx in loc:
            try:
                entry = self.df.loc[idx].logs
                _add(entry, name=f'loc_({idx})')

            except Exception as e:
                if verbose:
                    print(f'Exception for loc idx={idx} e={e}')

        for idx in iloc:
            try:
                entry = self.df.iloc[idx].logs
                _add(entry, name=f'ix_({idx})')

            except Exception as e:
                if verbose:
                    print(f'Exception for ix idx={idx} e={e}')

        ref = reference or []
        for i, (x, y) in enumerate(ref):
            data.append(Scatter(x=x, y=y, name=f'ref_{i}', mode=mode))

        plotly.offline.iplot({
            'data':
            data,
            'layout':
            Layout(autosize=False,
                   width=1000,
                   height=250,
                   margin=Margin(l=35, r=35, b=35, t=35, pad=0))
        })
Exemplo n.º 16
0
 def create_layout(self):
     return Layout(
         # title="Kamervragen per Week",
         xaxis=dict(title='Tijd'),
         yaxis=dict(title='Zetels per partij'),
         margin=Margin(t=20),
         legend=dict(
             # x=0.01,
             # y=1,
             bordercolor='#E2E2E2',
             bgcolor='#FFFFFF',
             borderwidth=2))
Exemplo n.º 17
0
    def get_context_data(self, **kwargs):
        import plotly.offline
        from plotly.graph_objs import Layout, Bar, Margin

        context = super().get_context_data(**kwargs)
        domains = self.get_domains()
        x = []
        y = []
        domains_selection = []
        min_mentions = 10
        for domain in domains:
            if domain[1] < min_mentions:
                break
            domains_selection.append(domain)
        for domain in reversed(domains):
            if domain[1] < 20:
                continue
            if domain[0] == 'zoek.officielebekendmakingen.nl':
                continue
            x.append(domain[0])
            y.append(domain[1])
        data = [Bar(
            x=y,
            y=x,
            orientation='h'
        )]
        plot_html = plotly.offline.plot(
            figure_or_data={
                "data": data,
                "layout": Layout(
                    title="Vermeldingen per website",
                    autosize=True,
                    height=1200,
                    margin=Margin(
                        l=200,
                        r=50,
                        b=40,
                        t=40,
                        pad=4
                    ),
                )
            },
            show_link=False,
            output_type='div',
            include_plotlyjs=False,
            auto_open=False,
        )
        context['plot_html'] = mark_safe(plot_html)
        context['domains'] = domains_selection
        context['min_mentions'] = min_mentions
        return context
Exemplo n.º 18
0
def _plotly_3d_scatter(coords, partition=None):
    """ _plotly_3d_scatter(coords, partition=None)

    Make a scatterplot of treeCl.CoordinateMatrix using the Plotly
    plotting engine
    """
    from plotly.graph_objs import Scatter3d, Data, Figure, Layout, Line, Margin, Marker
    # auto sign-in with credentials or use py.sign_in()

    colourmap = {
        'A': '#1f77b4',
        'B': '#ff7f0e',
        'C': '#2ca02c',
        'D': '#d62728',
        'E': '#9467bd',
        1: '#1f77b4',
        2: '#ff7f0e',
        3: '#2ca02c',
        4: '#d62728',
        5: '#9467bd'
    }

    df = coords.df
    if partition:
        assert len(partition.partition_vector) == df.shape[0]
        labels = [x + 1 for x in partition.partition_vector]
    else:
        labels = [1 for _ in range(df.shape[0])]

    x, y, z = df.columns[:3]
    df['Label'] = labels

    colours = [colourmap[lab] for lab in df['Label']]
    trace = Scatter3d(x=df[x],
                      y=df[y],
                      z=df[z],
                      mode='markers',
                      marker=Marker(size=9,
                                    color=colours,
                                    line=Line(color=colours, width=0.5),
                                    opacity=0.8),
                      text=[str(ix) for ix in df.index])

    data = Data([trace])
    layout = Layout(
        margin=Margin(l=0, r=0, b=0, t=0),
        hovermode='x',
    )
    fig = Figure(data=data, layout=layout)
    return fig
Exemplo n.º 19
0
def graphRes():
    conn = sqlite3.connect("test.db")
    sq = "SELECT title as Post_Title, sent as Sentiment_Analysis FROM merge;"
    df = pd.read_sql(sq, conn)

    plotly.offline.plot({
        "data": [Bar(x=df.Post_Title, y=df.Sentiment_Analysis)],
        "layout":
        Layout(
            title=
            "Comment Sentiment Analysis on Top 25 /r/worldnews Posts (from Last 24 Hrs)",
            margin=Margin(b=200))
    })

    #close connection
    conn.close()
Exemplo n.º 20
0
    def plotConfusionMatrix(self, data, normalize=True):
        """
    Plots the confusion matrix of the input dataframe.
    
    @param data         (pandas DF)     The confusion matrix.

    @param normalize    (bool)          True will normalize the confusion matrix
        values for the total number of actual classifications per label. Thus
        the cm values are 0.0 to 1.0.
    """
        xyzData = self.interpretConfusionMatrixData(data, normalize)

        data = Data([
            Heatmap(z=xyzData["z"],
                    x=xyzData["x"],
                    y=xyzData["y"],
                    colorscale='YIGnBu')
        ])

        layout = Layout(
            title='Confusion matrix for ' + self.experimentName,
            xaxis=XAxis(title='Predicted label',
                        side='top',
                        titlefont=Font(family='Courier New, monospace',
                                       size=18,
                                       color='#7f7f7f')),
            yaxis=YAxis(title='True label',
                        titlefont=Font(family='Courier New, monospace',
                                       size=18,
                                       color='#7f7f7f'),
                        autorange='reversed'),
            barmode='overlay',
            autosize=True,
            width=1000,
            height=1000,
            margin=Margin(l=200, r=80, b=80, t=450))

        fig = Figure(data=data, layout=layout)
        plot_url = py.plot(fig)
        print "Confusion matrix URL: ", plot_url
Exemplo n.º 21
0
         x2=[0, 1, 2, 3, 4, 5, 6],
         y2=[1, 4, 8, 16, 32, 64, 128])

SIMPLE_LINE = Figure(data=Data([
    Scatter(x=[0.0, 1.0, 2.0, 3.0, 4.0, 5.0],
            y=[10.0, 20.0, 50.0, 80.0, 100.0, 200.0],
            name='simple',
            mode='lines',
            line=Line(dash='solid', color='rgba (0, 0, 255, 1)', width=1.0),
            xaxis='x1',
            yaxis='y1')
]),
                     layout=Layout(width=640,
                                   height=480,
                                   autosize=False,
                                   margin=Margin(l=80, r=63, b=47, t=47,
                                                 pad=0),
                                   hovermode='closest',
                                   showlegend=False,
                                   xaxis1=XAxis(domain=[0.0, 1.0],
                                                range=[0.0, 5.0],
                                                type='linear',
                                                showline=True,
                                                ticks='inside',
                                                nticks=6,
                                                showgrid=False,
                                                zeroline=False,
                                                tickfont=Font(size=12.0),
                                                anchor='y1',
                                                side='bottom',
                                                mirror='ticks'),
                                   yaxis1=YAxis(domain=[0.0, 1.0],
Exemplo n.º 22
0
    def draw_igraph(self, title, colors=None):
        (Xn, Yn, Zn), (Xe, Ye, Ze) = self.get_3d_position()

        trace1 = Scatter3d(x=Xe,
                           y=Ye,
                           z=Ze,
                           mode='lines',
                           line=Line(color='rgb(125,125,125)',
                                     width=1,
                                     dash=True),
                           hoverinfo='none')

        trace2 = Scatter3d(
            x=Xn,
            y=Yn,
            z=Zn,
            mode='markers',
            name='callers',
            marker=Marker(
                symbol='dot',
                size=[100 * x + 5 for x in list(self.betweenness.values())],
                color=self.colors,
                colorscale='Rainbow',
                opacity=0.5),
            text=self.nodes,
            hoverinfo='text')

        axis = dict(showbackground=False,
                    showline=False,
                    zeroline=False,
                    showgrid=False,
                    showticklabels=False,
                    title='')
        layout = Layout(
            title=title,
            width=1000,
            height=1000,
            showlegend=False,
            scene=Scene(
                xaxis=XAxis(axis),
                yaxis=YAxis(axis),
                zaxis=ZAxis(axis),
            ),
            margin=Margin(t=100),
            hovermode='closest',
            annotations=Annotations([
                Annotation(showarrow=False,
                           text="Data source: ???",
                           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='Call Network')
Exemplo n.º 23
0
from plotly import __version__
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
from plotly.graph_objs import Scatter, Figure, Layout, Bar, Margin

import pandas as pd

df = pd.read_csv('data/recipeData.csv', index_col='BeerID', encoding='latin-1')
print(df.head())
print(df.info(verbose=False))
data = [
    Bar(
        x=df['Name'],  # assign x as the dataframe column 'x'
        y=df['OG'])
]
#url = plot(data, filename='graph/plot.html')

top_n_types = 15
recipe_popularity_as_perc = 100 * df['Style'].value_counts(
)[:top_n_types] / len(df)

data = [
    Bar(x=recipe_popularity_as_perc.index, y=recipe_popularity_as_perc.values)
]

layout = Layout(title='Most popular beer styles',
                xaxis={'title': 'Style'},
                yaxis={'title': 'Proportion of recipes (%)'},
                margin=Margin(l=50, r=50, b=150, t=50, pad=4))

fig = Figure(data=data, layout=layout)
plot(fig, filename='graph/popular.html')
Exemplo n.º 24
0
BLANK_SUBPLOTS = Figure(
    data=Data([
        Scatter(x=[0.0, 1.0],
                y=[1.0, 2.0],
                name='_line0',
                mode='lines',
                line=Line(dash='solid', color='#0000FF', width=1.0),
                xaxis='x1',
                yaxis='y1')
    ]),
    layout=Layout(
        width=640,
        height=480,
        autosize=False,
        margin=Margin(l=168, r=63, b=47, t=47, pad=0),
        hovermode='closest',
        showlegend=False,
        xaxis1=XAxis(domain=[0.0, 0.13513513513513517],
                     range=[0.0, 1.0],
                     type='linear',
                     showline=True,
                     ticks='inside',
                     nticks=6,
                     showgrid=False,
                     zeroline=False,
                     tickfont=Font(size=12.0),
                     anchor='y1',
                     side='bottom',
                     mirror='ticks'),
        xaxis2=XAxis(domain=[0.0, 0.13513513513513517],
Exemplo n.º 25
0
def draw3Dnx(graph=None,
             out_path=None,
             perc_threshold=None,
             positions_array=None,
             positions_dict=None,
             plot_title='',
             plot_description='',
             colorscale='Set3',
             notebook_mode=True,
             auto_open=False):
    """Draws a given graph in 3D"""

    if graph is None or nx.is_empty(graph):
        raise ValueError('input graph can not be empty!')
        # graph = nx.random_geometric_graph(200, 0.05)

    if notebook_mode:
        init_notebook_mode()

    marker_size = 7
    marker_edge_width = 2
    link_width = 2
    colorbar_title = 'Node Connections'
    hover_description = '# connections: '

    position_attr = ['x', 'y', 'z']
    if positions_array is not None:
        for node in graph.nodes():
            for ix, attr in enumerate(position_attr):
                graph.nodes[node][attr] = positions_array[node][ix]
    elif positions_dict is not None:
        for node in graph.nodes():
            for attr in position_attr:
                graph.nodes[node][attr] = positions_array[node][attr]

    for attr in position_attr:
        if not nx.get_node_attributes(graph, attr):
            raise ValueError(
                'Position attribute {} missing. '
                'Add it to graph or supply with one of the position inputs'.
                format(attr))

    edge_threshold = -np.Inf
    if perc_threshold is not None:
        eval_distr = np.array(
            list(nx.get_edge_attributes(graph, 'weight').values()))
        try:
            edge_threshold = np.percentile(eval_distr, perc_threshold)
        except:
            print('threshold to prune edges can not be determined.')
            traceback.print_exc()
            return

    edge_trace = Scatter3d(
        x=[],
        y=[],
        z=[],
        mode='lines',
        line=Line(width=marker_edge_width, color='#888'),
        hoverinfo='none',
    )

    def get_position(gnode):
        """Helper to retun the x, y, z coords of a node"""
        return gnode['x'], gnode['y'], gnode['z']

    for src, dest in graph.edges():
        # adding only the strongest edges
        if perc_threshold is None or graph.get_edge_data(
                src, dest)['weight'] > edge_threshold:
            x0, y0, z0 = get_position(graph.nodes[src])  # ['position']
            x1, y1, z1 = get_position(graph.nodes[dest])  # ['position']
            edge_trace['x'].extend([x0, x1, None])
            edge_trace['y'].extend([y0, y1, None])
            edge_trace['z'].extend([z0, z1, None])

    # empty lists here will be appended with data to be plotted
    node_trace = Scatter3d(x=[],
                           y=[],
                           z=[],
                           text=[],
                           mode='markers',
                           hoverinfo='text',
                           marker=Marker(
                               symbol='dot',
                               showscale=True,
                               colorscale=colorscale,
                               reversescale=True,
                               color=[],
                               size=marker_size,
                               colorbar=dict(thickness=15,
                                             title=colorbar_title,
                                             xanchor='left',
                                             titleside='right'),
                           ))

    # setting nodal positions and info
    for ix, node in enumerate(graph.nodes()):
        x, y, z = get_position(graph.nodes[node])
        node_trace['x'].append(x)
        node_trace['y'].append(y)
        node_trace['z'].append(z)
        node_trace['text'].append(node)
        node_trace['marker']['color'].append(ix)

    axis = dict(showbackground=False,
                showline=False,
                zeroline=False,
                showgrid=False,
                showticklabels=False,
                title='')

    scene = Scene(xaxis=XAxis(axis), yaxis=YAxis(axis), zaxis=ZAxis(axis))

    annotations = Annotations([
        Annotation(
            showarrow=False,
            text=plot_description,
            xref='paper',
            yref='paper',
            x=0,
            y=0.1,  # z=0.05,
            xanchor='left',
            yanchor='bottom',  # zanchor='bottom',
            font=Font(size=14))
    ])

    layout = Layout(
        title=plot_title,
        titlefont=dict(size=16),
        # width=1000,
        # height=1000,
        showlegend=False,
        hovermode='closest',
        scene=scene,
        margin=Margin(t=100),
        # margin=dict(b=20,l=5,r=5,t=40),
        annotations=annotations,
    )

    fig_data = Data([edge_trace, node_trace])

    fig = Figure(data=fig_data, layout=layout)

    if out_path is None and auto_open is False:
        auto_open = True

    if notebook_mode:
        iplot(fig, filename=out_path)
    else:
        plot(fig, filename=out_path, auto_open=auto_open)

    return fig
Exemplo n.º 26
0
          showticklabels=False,
          title=''
          )

layout = Layout(
         title="Link Structure for Delhi University - Academics",
         width=1000,
         height=1000,
         showlegend=False,
         scene=Scene(
         xaxis=XAxis(axis),
         yaxis=YAxis(axis),
         zaxis=ZAxis(axis),
        ),
     margin=Margin(
        t=100
    ),
    hovermode='closest',
    annotations=Annotations([
           Annotation(
           showarrow=False,
            text="",
            xref='paper',
            yref='paper',
            x=0,
            y=0.1,
            xanchor='left',
            yanchor='bottom',
            font=Font(
            size=14
            )
Exemplo n.º 27
0
 def create_layout(self):
     return Layout(
         # title="Dagen tot Antwoord",
         xaxis=dict(title='Antwoordtijd [dagen]'),
         yaxis=dict(title='Aantal Kamervragen'),
         margin=Margin(t=20))
Exemplo n.º 28
0
def plotCorrelations(fileNameP, listP):
    import plotly.plotly as py
    #import plotly
    from plotly.graph_objs import Bar, Marker, Data, Layout, XAxis, YAxis, Figure, Margin, Font
    #import plotly.graph_objs as gObjLib
    ### authentication stuff ....
    #py = plotly.plotly(username='******', key='9ebth53cdo')
    #barSize = 5
    fileTrace = [listP[0], listP[1], listP[2]]
    projectTrace = [listP[3], listP[4], listP[5]]
    stateTrace = [listP[6], listP[7], listP[8]]
    namespaceTrace = [listP[9], listP[10], listP[11]]

    fileCorrTrace = Bar(
        x=['Corr. >= 0.50', 'Corr. within 0.0 & 0.499', 'Corr. < 0.0'],
        #x=[ 'Idle', 'System', 'Code', 'Debug', 'Build'],
        y=fileTrace,
        name='FileInterleaving')

    projCorrTrace = Bar(
        x=['Corr. >= 0.50', 'Corr. within 0.0 & 0.499', 'Corr. < 0.0'],
        #x=[ 'Idle', 'System', 'Code', 'Debug', 'Build'],
        y=projectTrace,
        name='ProjetInterleaving')

    nspaceCorrTrace = Bar(
        x=['Corr. >= 0.50', 'Corr. within 0.0 & 0.499', 'Corr. < 0.0'],
        #x=[ 'Idle', 'System', 'Code', 'Debug', 'Build'],
        y=namespaceTrace,
        name='NamespaceInterleaving')

    stateTrace = Bar(
        x=['Corr. >= 0.50', 'Corr. within 0.0 & 0.499', 'Corr. < 0.0'],
        #x=[ 'Idle', 'System', 'Code', 'Debug', 'Build'],
        y=stateTrace,
        name='StateInterleaving')

    #fileCorrTrace['marker'] = Marker(color='blue', size=barSize)
    #projCorrTrace['marker'] = Marker(color='green', size=barSize)
    #nspaceCorrTrace['marker'] = Marker(color='yellow', size=barSize)
    #stateTrace['marker'] = Marker(color='red', size=barSize)
    fileCorrTrace['marker'] = Marker(color='blue')
    projCorrTrace['marker'] = Marker(color='green')
    nspaceCorrTrace['marker'] = Marker(color='yellow')
    stateTrace['marker'] = Marker(color='red')
    dataToPlot = Data(
        [fileCorrTrace, projCorrTrace, nspaceCorrTrace, stateTrace])

    layoutToUse = Layout(
        title='Distribution of Correlation for 339 Datasets : ' + fileNameP,
        titlefont=Font(family='Times New Roman', size=18, color='#000000'),
        barmode='group',
        xaxis=XAxis(showgrid=True,
                    showline=True,
                    title='Interleaving Correlations',
                    titlefont=Font(family='Times New Roman',
                                   size=12,
                                   color='#000000'),
                    tickwidth=1.5),
        yaxis=YAxis(
            showgrid=True,
            showline=True,
            title='Count',
            #range=[0, 35],
            autorange=True,
            titlefont=Font(family='Times New Roman', size=12,
                           color='#000000')),
        width=800,
        height=600,
        margin=Margin(l=140, r=40, b=50, t=80),
    )
    fileToSave = 'plots/' + fileNameP + '.png'
    figToPlot = Figure(data=dataToPlot, layout=layoutToUse)
    py.image.save_as(figToPlot, fileToSave)
Exemplo n.º 29
0
def plotLinesForBaseline(fileNameParam):
    import csv
    import plotly.plotly as py
    import plotly.graph_objs as go
    from plotly.graph_objs import Layout, YAxis, Figure, Margin, Font, XAxis

    xList = []
    baselineAct = []
    optimizedAct = []
    baselinePass = []
    optimizedPass = []

    fileToRead = open(fileNameParam, "rU")
    try:
        fileReader = csv.reader(fileToRead,
                                delimiter=',',
                                dialect=csv.excel_tab)
        next(fileReader, None)
        for rowVar in fileReader:
            xList.append(rowVar[0])
            baselineAct.append(rowVar[1])
            optimizedAct.append(rowVar[3])
            baselinePass.append(rowVar[2])
            optimizedPass.append(rowVar[4])
    finally:
        fileToRead.close()

    baselineActTrace = go.Scatter(x=xList,
                                  y=baselineAct,
                                  mode='lines+markers',
                                  name='Baseline-Undetected Active Errors')
    optimizedActTrace = go.Scatter(x=xList,
                                   y=optimizedAct,
                                   mode='lines+markers',
                                   name='Optimized-Undetected Active Errors')
    baselinePassTrace = go.Scatter(x=xList,
                                   y=baselinePass,
                                   mode='lines+markers',
                                   name='Baseline-Undetected Passive Errors')
    optimizedPassTrace = go.Scatter(x=xList,
                                    y=optimizedPass,
                                    mode='lines+markers',
                                    name='Optimized-Undetected Passive Errors')
    ActTraces = [baselineActTrace, optimizedActTrace]
    PassTraces = [baselinePassTrace, optimizedPassTrace]
    layout_ActError = Layout(
        title=
        'Comparing Optimized Values with Baseline Values : Undetected Active Errors',
        titlefont=Font(family='Times New Roman', size=18, color='#000000'),
        xaxis=XAxis(showgrid=True,
                    showline=True,
                    title='Iterations of DE',
                    autorange=False,
                    range=[0, 1100],
                    titlefont=Font(family='Times New Roman',
                                   size=12,
                                   color='#000000')),
        yaxis=YAxis(showgrid=True,
                    showline=True,
                    title='Optimized Value',
                    range=[0, 1500],
                    autorange=False,
                    titlefont=Font(family='Times New Roman',
                                   size=12,
                                   color='#000000')),
        width=800,
        height=600,
        margin=Margin(l=140, r=40, b=50, t=80),
    )

    layout_PassError = Layout(
        title=
        'Comparing Optimized Values with Baseline Values : Undetected Passive Errors',
        titlefont=Font(family='Times New Roman', size=18, color='#000000'),
        xaxis=XAxis(showgrid=True,
                    showline=True,
                    title='Iterations of DE',
                    autorange=False,
                    range=[0, 1100],
                    titlefont=Font(family='Times New Roman',
                                   size=12,
                                   color='#000000')),
        yaxis=YAxis(showgrid=True,
                    showline=True,
                    title='Optimized Value',
                    range=[0, 5],
                    autorange=False,
                    titlefont=Font(family='Times New Roman',
                                   size=12,
                                   color='#000000')),
        width=800,
        height=600,
        margin=Margin(l=140, r=40, b=50, t=80),
    )

    fig_UnActErr = Figure(data=ActTraces, layout=layout_ActError)
    fileNameParam = "UnActError.png"
    py.image.save_as(fig_UnActErr, fileNameParam)

    fig_UnPassErr = Figure(data=PassTraces, layout=layout_PassError)
    fileNameParam = "UnPassError.png"
    py.image.save_as(fig_UnPassErr, fileNameParam)

    return "DONE!"
Exemplo n.º 30
0
def plotAllStates(fileNameP, dictP):
    import plotly.plotly as py
    from plotly.graph_objs import Bar, Marker, Data, Layout, XAxis, YAxis, Figure, Margin, Font
    #import plotly.graph_objs as gObjLib
    #####
    dirToSave = "plotsesscat/"
    #barSize = 6
    listForNormalTrace = []
    listForHeavyTrace = []
    listForSuperHeavyTrace = []
    allCatList = ['None', 'Idle', 'System', 'Code', 'Debug', 'Build', 'Navi']
    for it_ in allCatList:
        #print "ZZZZZZZ", dictP[it_]
        listForNormalTrace.append(dictP[it_][0])
        listForHeavyTrace.append(dictP[it_][1])
        listForSuperHeavyTrace.append(dictP[it_][2])

    #print "length - Normal ... ", listForNormalTrace
    #print "length - Heavy ... ", listForHeavyTrace
    #print "length - SuperHeavy ... ", listForSuperHeavyTrace
    normalTrace = Bar(
        x=['None', 'Idle', 'System', 'Code', 'Debug', 'Build', 'Navi'],
        #x=[ 'Idle', 'System', 'Code', 'Debug', 'Build'],
        y=listForNormalTrace,
        name='Normal')

    heavyTrace = Bar(
        x=['None', 'Idle', 'System', 'Code', 'Debug', 'Build', 'Navi'],
        #x=[ 'Idle', 'System', 'Code', 'Debug', 'Build'],
        y=listForHeavyTrace,
        name='Heavy')

    superHeavyTrace = Bar(
        x=['None', 'Idle', 'System', 'Code', 'Debug', 'Build', 'Navi'],
        #x=[ 'Idle', 'System', 'Code', 'Debug', 'Build'],
        y=listForSuperHeavyTrace,
        name='Super Heavy')

    normalTrace['marker'] = Marker(color='green')
    heavyTrace['marker'] = Marker(color='yellow')
    superHeavyTrace['marker'] = Marker(color='red')
    dataToPlot = Data([normalTrace, heavyTrace, superHeavyTrace])

    layoutToUse = Layout(
        title='Distribution of Different Session Categories',
        titlefont=Font(family='Times New Roman', size=22, color='#000000'),
        barmode='group',
        xaxis=XAxis(showgrid=True,
                    showline=True,
                    title='Types of Sessions',
                    titlefont=Font(family='Times New Roman',
                                   size=18,
                                   color='#000000'),
                    tickwidth=1.5),
        yaxis=YAxis(
            showgrid=True,
            showline=True,
            title='Count',
            #range=[0, 35],
            autorange=True,
            titlefont=Font(family='Times New Roman', size=18,
                           color='#000000')),
        width=800,
        height=600,
        margin=Margin(l=140, r=40, b=50, t=80),
    )
    fileToSave = dirToSave + fileNameP + '.png'
    figToPlot = Figure(data=dataToPlot, layout=layoutToUse)
    #plot_url = py.plot(figToPlot, filename=fileToSave)
    py.image.save_as(figToPlot, fileToSave)