示例#1
0
 def test_update_dict(self):
     title = 'this'
     fig = Figure()
     fig.update(layout=Layout(title=title))
     assert fig == Figure(layout=Layout(title=title))
     fig['layout'].update(xaxis=XAxis())
     assert fig == Figure(layout=Layout(title=title, xaxis=XAxis()))
 def test_update_dict(self):
     title = "this"
     fig = Figure()
     update_res1 = fig.update(layout=Layout(title=title))
     assert fig == Figure(layout=Layout(title=title))
     update_res2 = fig["layout"].update(xaxis=XAxis())
     assert fig == Figure(layout=Layout(title=title, xaxis=XAxis()))
     assert update_res1 is fig
     assert update_res2 is fig.layout
示例#3
0
def test_two_row():
    expected = Figure(data=Data(),
                      layout=Layout(xaxis1=XAxis(domain=[0.0, 1.0],
                                                 anchor='y1'),
                                    xaxis2=XAxis(domain=[0.0, 1.0],
                                                 anchor='y2'),
                                    yaxis1=YAxis(domain=[0.0, 0.425],
                                                 anchor='x1'),
                                    yaxis2=YAxis(domain=[0.575, 1.0],
                                                 anchor='x2')))
    assert tls.get_subplots(2) == expected
示例#4
0
 def _createLayout(title=None,
                   xLabel="Date",
                   yLabel="Metric",
                   fontSize=12,
                   width=WIDTH,
                   height=HEIGHT):
     """Return plotly Layout object."""
     layoutArgs = {
         "title": title,
         "font": {
             "size": fontSize
         },
         "showlegend": False,
         "width": width,
         "height": height,
         "xaxis": XAxis(title=xLabel, ),
         "yaxis": YAxis(
             title=yLabel,
             domain=[0, 1],
             autorange=True,
         ),
         "barmode": "stack",
         "bargap": 0
     }
     margins = {"l": 70, "r": 30, "b": 50, "t": 90, "pad": 4}
     if title is None:
         margins["t"] -= 70
     if fontSize > 12:
         margins["l"] += (fontSize - 12) * 3
         margins["b"] += (fontSize - 12) * 3
     layoutArgs["margin"] = margins
     return Layout(**layoutArgs)
示例#5
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
def plot_explained_variance(pca):
    explained_var = pca.explained_variance_ratio_
    cum_var_exp = np.cumsum(explained_var)

    py.iplot(Figure(
        data=[
            Bar(y=explained_var, name='individual explained variance'),
            Scatter(y=cum_var_exp, name='cumulative explained variance'),
        ],
        layout=\
            Layout(xaxis=XAxis(title='Principal components'),
                   yaxis=YAxis(title='Explained variance ratio'),
                   shapes=[{
                                               'type': 'line',
                            'xref': 'paper',
                            'x0': 0,
                            'y0': 1 / len(explained_var), # use absolute value or variable here
                            'x1': 1,
                            'y1': 1 / len(explained_var), # ditto
                       'line': {
                                'color': 'rgb(50, 171, 96)',
                                'width': 2,
                                'dash': 'dash',
                            },}]
                   )
    ))
示例#7
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)
示例#8
0
    def init_layout(self, key, element, ranges):
        l, b, zmin, r, t, zmax = self.get_extents(element, ranges)

        xd, yd, zd = (element.get_dimension(i) for i in range(3))
        xaxis = dict(range=[l, r], title=str(xd))
        if self.logx:
            xaxis['type'] = 'log'

        yaxis = dict(range=[b, t], title=str(yd))
        if self.logy:
            yaxis['type'] = 'log'

        zaxis = dict(range=[zmin, zmax], title=str(zd))
        if self.logz:
            zaxis['type'] = 'log'

        opts = {}
        if self.aspect == 'cube':
            opts['aspectmode'] = 'cube'
        else:
            opts['aspectmode'] = 'manual'
            opts['aspectratio'] = self.aspect
        scene = Scene(xaxis=XAxis(xaxis),
                      yaxis=YAxis(yaxis),
                      zaxis=ZAxis(zaxis),
                      **opts)

        return dict(width=self.width,
                    height=self.height,
                    title=self._format_title(key, separator=' '),
                    plot_bgcolor=self.bgcolor,
                    scene=scene)
示例#9
0
def createLayout(title=None,
                 xLabel="Date",
                 yLabel="Metric",
                 fontSize=12,
                 width=800,
                 height=500):
    """Return plotly Layout object."""
    layoutArgs = {
        "title": title,
        "font": {
            "size": fontSize
        },
        "showlegend": False,
        "width": width,
        "height": height,
        "xaxis": XAxis(title=xLabel, ),
        "yaxis": YAxis(
            title=yLabel,
            domain=[0, 1],
            autorange=True,
            autotick=True,
        ),
        "barmode": "stack",
        "bargap": 0
    }
    margins = {"l": 70, "r": 30, "b": 50, "t": 90, "pad": 4}
    layoutArgs["margin"] = margins
    return Layout(**layoutArgs)
def results(symbol, trend1, trend2):
    data = web.DataReader(symbol, data_source='yahoo')

    #Guardamos la data en formato HDF5
    #    filename = 'data'+'_'+symbol+'_'+trend1+'_'+trend2+'.h5'
    filename = 'data.h5'
    store = {}

    store['symbol'] = data
    h5 = pd.HDFStore(filename, 'w')
    h5['symbol'] = store['symbol']
    h5.close()

    #Mandamos la data al correo
    #os.system("python send_email.py")

    data['Tendencia 1'] = pd.rolling_mean(data['Adj Close'],
                                          window=int(trend1))
    data['Tendencia 2'] = pd.rolling_mean(data['Adj Close'],
                                          window=int(trend2))
    layout = Layout(xaxis=XAxis(showgrid=True,
                                gridcolor='#bdbdbd',
                                gridwidth=2),
                    yaxis=YAxis(showgrid=True,
                                gridcolor='#bdbdbd',
                                gridwidth=2))
    fig = Figure(data=df_to_plotly(
        data[['Adj Close', 'Tendencia 1', 'Tendencia 2']]),
                 layout=layout)
    plot = ply.plot(fig, auto_open=False)
    table = data.tail().to_html()
    return render_template('plotly.html',
                           symbol=symbol,
                           plot=plot,
                           table=table)
示例#11
0
def test_get_single_plot():
    expected = Figure(data=Data(),
                      layout=Layout(xaxis1=XAxis(domain=[0.0, 1.0],
                                                 anchor='y1'),
                                    yaxis1=YAxis(domain=[0.0, 1.0],
                                                 anchor='x1')))
    assert tls.get_subplots() == expected
示例#12
0
def plot_linear_prediction(results, data, filename):
    x_transform = (add_month(data[0][-1]) - min(data[0])).days
    x_val = add_month(data[0][-1])
    prediction = results.params["x"] * x_transform + results.params["Intercept"]
    trace1 = Scatter(x=data[0],
                     y=data[1],
                     mode='lines',
                     marker=Marker(color='rgb(255, 127, 14)'),
                     name='Data')

    trace2 = Scatter(x=[x_val],
                     y=[prediction],
                     mode='markers',
                     marker=Marker(color='rgb(31, 119, 180)'),
                     name='Fit')

    layout = Layout(title='Linear Fit in Python',
                    plot_bgcolor='rgb(229, 229, 229)',
                    xaxis=XAxis(zerolinecolor='rgb(255,255,255)',
                                gridcolor='rgb(255,255,255)'),
                    yaxis=YAxis(zerolinecolor='rgb(255,255,255)',
                                gridcolor='rgb(255,255,255)'))

    to_scatter = [trace1, trace2]
    plotly.offline.plot({"data": to_scatter, "layout": layout})

    shutil.move("temp-plot.html", filename)
示例#13
0
def init_plotly():
    """
    Prepares authenticate tokens for each trace, prepares layout and streams with corresponding scatter graph traces.

    :return: Returns initialized stream IDs for each trace
    """
    logger = logging.getLogger(sys._getframe().f_code.co_name)

    # pull in Plotly authentication data
    plotly_creds = plotly.tools.get_credentials_file()
    username = plotly_creds['username']
    api_key = plotly_creds['api_key']
    token_cpu, token_temp, token_humidity, token_pressure, token_wu = plotly_creds['stream_ids'][0:5]

    plotly.plotly.sign_in(username, api_key)

    # create Stream structures with proper tokens and maximum preserved graph points
    my_stream_cpu = Stream(token=token_cpu, maxpoints=MAX_POINTS)
    my_stream_temp = Stream(token=token_temp, maxpoints=MAX_POINTS)
    my_stream_humidity = Stream(token=token_humidity, maxpoints=MAX_POINTS)
    my_stream_pressure = Stream(token=token_pressure, maxpoints=MAX_POINTS)
    my_stream_wu = Stream(token=token_wu, maxpoints=MAX_POINTS)

    # create Scatter-type structures with appropriate names; don't provide sample data as we'll provide it live in
    # Stream mode
    my_scatter_cpu = Scatter(x=[], y=[], stream=my_stream_cpu, name='CPU temperature', mode=TRACE_MODE)
    my_scatter_temp = Scatter(x=[], y=[], stream=my_stream_temp,
                              name='Environment temperature', mode=TRACE_MODE)
    my_scatter_humidity = Scatter(x=[], y=[], stream=my_stream_humidity,
                                  name='Environment humidity', mode=TRACE_MODE)
    my_scatter_pressure = Scatter(x=[], y=[], stream=my_stream_pressure,
                                  name='Barometric pressure', yaxis='y2',
                                  mode=TRACE_MODE)
    my_scatter_wu = Scatter(x=[], y=[], stream=my_stream_wu, name='Outdoor temperature (Weather Underground)',
                            mode=TRACE_MODE)

    # prepare Data structure
    my_data = Data([my_scatter_cpu, my_scatter_temp, my_scatter_humidity,
                    my_scatter_pressure, my_scatter_wu])

    # create Layout structure where we have one shared X axis (time series) and two Y axis, one left side (temperature
    # and humidity) and one right side (pressure)
    my_layout = Layout(title='Raspberry PI Sensors',
                       xaxis=XAxis(title='Time'), yaxis=YAxis(title='Temperature [C] / Humidity [%]'),
                       yaxis2=YAxis(title='Pressure [hPa]',
                                    overlaying='y', side='right',
                                    titlefont=Font(color='rgb(148, 103, 189)'),
                                    tickfont=Font(color='rgb(148, 103, 189)')))

    # prepare Figure structure
    my_fig = Figure(data=my_data, layout=my_layout)

    try:
        # overwrite existing data on creating the new figure
        plotly.plotly.plot(my_fig, filename=PLOTLY_CHART_NAME, auto_open=False, fileopt=GRAPH_MODE)
    except requests.exceptions.ConnectionError, e:
        logger.error('Cannot connect to PlotLy to create chart: %s. Exiting...' % e)
        sys.exit(1)
示例#14
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)))
示例#15
0
def plot_df(df, title):
    ax = ['x', 'y', 'z']
    data = [Scatter(y=df[a], name=a) for a in ax]

    layout = Layout(title=title,
                    xaxis=XAxis(title='Timestep'),
                    yaxis=YAxis(title='{x, y, z} coordinates in Gs'))

    plot({'data': data, 'layout': layout}, show_link=False)
示例#16
0
def scatter_df_plotly(df,
                      x,
                      y,
                      z,
                      text_fnct=hover_all,
                      streaming=True,
                      filename=None):
    """
    a wrapper function for `plotlyi.graph_objs.Scatter` on `pandas.Dataframe`

    usage:
    =====
    d

    """
    layout = Layout(
        title='colour map: %s' % z,
        hovermode='closest',  # (!) hover -> closest data pt
        showlegend=False,  # remove legend (info in hover)
        autosize=False,  # turn off autosize
        width=650,  # plot width
        height=500,  # plot height
        xaxis=XAxis(title=x,
                    titlefont=Font(family='Courier New, monospace',
                                   size=14,
                                   color='#7f7f7f')),
        yaxis=YAxis(title=y,
                    titlefont=Font(family='Courier New, monospace',
                                   size=14,
                                   color='#7f7f7f')))
    #    print('marker sizes:')
    #    print(rescale_marker(df[z], square = True))
    SC = Scatter(x=df[x],
                 y=df[y],
                 mode='markers',
                 marker=Marker(size=rescale_marker(df[z], square=True),
                               color=df[z],
                               colorscale='Jet',
                               sizeref=1,
                               sizemode='area'))

    FIG = Figure(data=Data([SC]), layout=layout)
    #FIG['layout'].update( )

    if text_fnct is not None:
        FIG['data'][0].update(text = \
        df.apply(lambda ds: text_fnct(ds, x=x, y=y,z=z), axis = 1).tolist()  )

    if not streaming:
        if filename is not None:
            return py.plot(FIG, filename=filename)
        else:
            return py.plot(FIG)
    else:
        return py.iplot(FIG)
示例#17
0
def test_append_scatter():
    expected = Figure(
        data=Data([Scatter(x=[1, 2, 3], y=[2, 3, 4], xaxis="x5", yaxis="y5")]),
        layout=Layout(
            xaxis1=XAxis(domain=[0.0, 0.2888888888888889], anchor="y1"),
            xaxis2=XAxis(domain=[0.35555555555555557, 0.6444444444444445],
                         anchor="y2"),
            xaxis3=XAxis(domain=[0.7111111111111111, 1.0], anchor="y3"),
            xaxis4=XAxis(domain=[0.0, 0.2888888888888889], anchor="y4"),
            xaxis5=XAxis(domain=[0.35555555555555557, 0.6444444444444445],
                         anchor="y5"),
            xaxis6=XAxis(domain=[0.7111111111111111, 1.0], anchor="y6"),
            yaxis1=YAxis(domain=[0.575, 1.0], anchor="x1"),
            yaxis2=YAxis(domain=[0.575, 1.0], anchor="x2"),
            yaxis3=YAxis(domain=[0.575, 1.0], anchor="x3"),
            yaxis4=YAxis(domain=[0.0, 0.425], anchor="x4"),
            yaxis5=YAxis(domain=[0.0, 0.425], anchor="x5"),
            yaxis6=YAxis(domain=[0.0, 0.425], anchor="x6"),
        ),
    )

    trace = Scatter(x=[1, 2, 3], y=[2, 3, 4])
    fig = tls.make_subplots(rows=2, cols=3)
    fig.append_trace(trace, 2, 2)

    d1, d2 = strip_dict_params(fig["data"][0], expected["data"][0])
    assert d1 == d2

    d1, d2 = strip_dict_params(fig["layout"], expected["layout"])
    assert d1 == d2
示例#18
0
def test_append_scatter():
    expected = Figure(
        data=Data([Scatter(x=[1, 2, 3], y=[2, 3, 4], xaxis='x5', yaxis='y5')]),
        layout=Layout(
            xaxis1=XAxis(domain=[0.0, 0.2888888888888889], anchor='y1'),
            xaxis2=XAxis(domain=[0.35555555555555557, 0.6444444444444445],
                         anchor='y2'),
            xaxis3=XAxis(domain=[0.7111111111111111, 1.0], anchor='y3'),
            xaxis4=XAxis(domain=[0.0, 0.2888888888888889], anchor='y4'),
            xaxis5=XAxis(domain=[0.35555555555555557, 0.6444444444444445],
                         anchor='y5'),
            xaxis6=XAxis(domain=[0.7111111111111111, 1.0], anchor='y6'),
            yaxis1=YAxis(domain=[0.575, 1.0], anchor='x1'),
            yaxis2=YAxis(domain=[0.575, 1.0], anchor='x2'),
            yaxis3=YAxis(domain=[0.575, 1.0], anchor='x3'),
            yaxis4=YAxis(domain=[0.0, 0.425], anchor='x4'),
            yaxis5=YAxis(domain=[0.0, 0.425], anchor='x5'),
            yaxis6=YAxis(domain=[0.0, 0.425], anchor='x6')))

    trace = Scatter(x=[1, 2, 3], y=[2, 3, 4])
    fig = tls.make_subplots(rows=2, cols=3)
    fig.append_trace(trace, 2, 2)

    d1, d2 = strip_dict_params(fig['data'][0], expected['data'][0])
    assert d1 == d2

    d1, d2 = strip_dict_params(fig['layout'], expected['layout'])
    assert d1 == d2
示例#19
0
 def _createLayout(title):
     """Return plotly Layout object."""
     return Layout(title=title,
                   showlegend=False,
                   width=1000,
                   height=600,
                   xaxis=XAxis(title="Date"),
                   yaxis=YAxis(title="Metric",
                               domain=[0, 1],
                               autorange=True,
                               autotick=True),
                   barmode="stack",
                   bargap=0)
示例#20
0
def plot_explained_variance(pca):
    import plotly
    from plotly.graph_objs import Scatter, Marker, Layout, XAxis, YAxis, Bar, Line
    plotly.offline.init_notebook_mode() # run at the start of every notebook
    
    explained_var = pca.explained_variance_ratio_
    cum_var_exp = np.cumsum(explained_var)
    
    plotly.offline.iplot({
        "data": [Bar(y=explained_var, name='individual explained variance'),
                 Scatter(y=cum_var_exp, name='cumulative explained variance')
            ],
        "layout": Layout(xaxis=XAxis(title='Principal components'), yaxis=YAxis(title='Explained variance ratio'))
    })
示例#21
0
def results(symbol, trend1, trend2):
    data = web.DataReader(symbol, data_source='yahoo')
    data['Trend 1'] = pd.rolling_mean(data['Adj Close'], window=int(trend1))
    data['Trend 2'] = pd.rolling_mean(data['Adj Close'], window=int(trend2))
    layout = Layout(
        xaxis=XAxis(showgrid=True, gridcolor='#bdbdbd', gridwidth=2),
        yaxis=YAxis(showgrid=True, gridcolor='#bdbdbd', gridwidth=2)
    )
    fig = Figure(data=df_to_plotly(data[['Adj Close', 'Trend 1', 'Trend 2']]),
                layout=layout)
    plot = ply.plot(fig, auto_open=False)
    table = data.tail().to_html()
    return render_template('plotly.html', symbol=symbol,
                            plot=plot, table=table)
def fig1():
    trace1 = Scatter(
            x=df['LifeExpectancy'],
            y=df['GNP'],
            text=country_names,
            mode='markers'
    )
    layout = Layout(
            xaxis=XAxis(title='Life Expectancy'),
            yaxis=YAxis(type='log', title='GNP')
    )
    data = Data([trace1])
    fig = Figure(data=data, layout=layout)
    py.iplot(fig, filename='world GNP vs life expectancy')
示例#23
0
def plotly_create_stream(data):
    api_key = os.environ.get("PLOTLY_KEY_API")
    stream_token = os.environ.get("PULSE_STREAM_TOKEN")
    x, y = process_data_for_pulse(data)
    py.sign_in('SergeyParamonov', api_key)
    data = Data([Scatter(x=x, y=y, stream=dict(token=stream_token))])
    layout = Layout(
        title="Пульс Хабра — изменение просмотров статей в Новом (в минуту)",
        xaxis=XAxis(title=u"Московское время"),  # x-axis title
        yaxis=YAxis(title=u"Просмотры"),  # y-axis title
        showlegend=False,  # remove legend (info in hover)
        hovermode='closest',  # N.B hover -> closest data pt
    )
    plotly_fig = Figure(data=data, layout=layout)
    unique_url = py.plot(plotly_fig, filename="pulse")
    return unique_url
def biplot(pca, dat, title='', show_points=True, components=(0, 1)):
    import plotly
    from plotly.graph_objs import Scatter, Marker, Layout, XAxis, YAxis, Bar, Line
    plotly.offline.init_notebook_mode()  # run at the start of every notebook

    pc1, pc2 = components

    # 0,1 denote PC1 and PC2; change values for other PCs
    xvector = pca.components_[pc1]
    yvector = pca.components_[pc2]

    tmp = pca.transform(dat.values)
    xs = tmp[:, pc1]
    ys = tmp[:, pc2]
    if show_points:
        annotations = [
            Scatter(x=xs,
                    y=ys,
                    mode='markers',
                    marker=dict(size=1),
                    name='cumulative explained variance')
        ]
    else:
        annotations = []
    for i in range(len(xvector)):
        txt = list(dat.columns.values)[i]
        annotations.append(
            Scatter(
                x=[0, xvector[i] * max(xs)],
                y=[0, yvector[i] * max(ys)],
                mode='lines+text',
                text=['', txt],
                name=txt,
            ))

    plotly.offline.iplot({
        "data":
        annotations,
        "layout":
        Layout(xaxis=XAxis(title='Principal Component ' + str(pc1 + 1)),
               yaxis=YAxis(title='Principal Component ' + str(pc2 + 1)),
               title=title)
    })

    plt.show()
示例#25
0
def visualize_shares_post(dates, vk, fb, tw, post_id, title):
    locale.setlocale(locale.LC_ALL, 'en_US.utf8')
    api_key = os.environ.get("PLOTLY_KEY_API")
    py.sign_in('SergeyParamonov', api_key)
    vk_trace = Scatter(x=dates, y=vk, mode='lines+markers', name=u"Вконтакте")
    fb_trace = Scatter(x=dates, y=fb, mode='lines+markers', name=u"Facebook")
    tw_trace = Scatter(x=dates, y=tw, mode='lines+markers', name=u"Twitter")
    data = Data([vk_trace, fb_trace, tw_trace])
    layout = Layout(
        title=u"Репосты: " + title,
        xaxis=XAxis(title=u"Московское время"),  # x-axis title
        yaxis=YAxis(title=u"Репосты"),  # y-axis title
        hovermode='closest',  # N.B hover -> closest data pt
    )
    plotly_fig = Figure(data=data, layout=layout)
    plotly_filename = "monitor_post_id_" + str(post_id) + "_" + "shares"
    unique_url = py.plot(plotly_fig, filename=plotly_filename)
    return unique_url
示例#26
0
def visualize_post_plotly(x, y, field, post_id, title):
    api_key = os.environ.get("PLOTLY_KEY_API")
    py.sign_in('SergeyParamonov', api_key)
    data = Data([Scatter(x=x, y=y)])
    if field == "favorite":
        ytitle = u"Избранное"
    else:
        ytitle = u"Просмотры"
    layout = Layout(
        title=ytitle + ": " + title,
        xaxis=XAxis(title=u"Московское время"),  # x-axis title
        yaxis=YAxis(title=ytitle),  # y-axis title
        showlegend=False,  # remove legend (info in hover)
        hovermode='closest',  # N.B hover -> closest data pt
    )
    plotly_fig = Figure(data=data, layout=layout)
    plotly_filename = "monitor_post_id_" + str(post_id) + "_" + field
    unique_url = py.plot(plotly_fig, filename=plotly_filename)
    return unique_url
示例#27
0
def init_plotly():
    import locale
    try:
        locale.setlocale(locale.LC_ALL, 'de_DE')
    except locale.Error:
        locale.setlocale(locale.LC_ALL, 'deu_deu')
    from sys import stdout
    stdout.write("init plotly..")
    global plot, Scatter, Layout, Bar, Xaxis, YAxis, Legend, Marker, Annotation
    global bar, scatter, layout, data, last_bar, day_line, day_marker
    from plotly.offline import plot
    from plotly.graph_objs import Scatter, Layout, Bar, XAxis, YAxis, Legend, Marker, Annotation

    # data
    bar = Bar(x=[], y=[], name='Aktueller Verbrauch')
    last_bar = Bar(x=[],
                   y=[],
                   name='Bisheriger Verbrauch<br>in aktueller Stunde',
                   marker=dict(color='rgb(159, 197, 232)'))
    scatter = Scatter(x=[],
                      y=[],
                      name='Durchschnittlicher Verbrauch',
                      mode="lines+markers")

    #layout
    layout = Layout(
        title="Stromverbrauch der letzten 24 Stunden",
        barmode='stacked',
        xaxis=XAxis(tickmode='array',
                    ticktext=[],
                    tickvals=[],
                    range=[-0.5, 1],
                    tickangle=-45),
        yaxis=YAxis(title='Wh'),
        legend=Legend(bordercolor='#FFFFFF',
                      borderwidth=3,
                      xanchor="right",
                      x=1.0,
                      y=1.11)  # bgcolor='#E2E2E2'
    )

    data = {"data": [bar, scatter, last_bar], "layout": layout}
    print(" done")
示例#28
0
    def plotBucketsMetrics(self, metricsDict, comboMethod, numIterations,
                           modelName):
        """
    @param metricsDicts   (dict)  Arrays for the min, mean, and max of each
                                  metric.
    @param comboMethod    (str)   Concatenation method from the experiment.
    @param numIterations  (str)   Number of inference steps run.
    @param modelName      (str)   Name of tested model.
    """
        xData = range(1, numIterations + 1)

        for metricName, results in metricsDict.iteritems():
            if metricName == "totalRanked": continue
            minTrace = Scatter(x=xData,
                               y=results[0],
                               mode="lines+markers",
                               name="min")
            meanTrace = Scatter(x=xData,
                                y=results[1],
                                mode="lines+markers",
                                name="mean")
            maxTrace = Scatter(x=xData,
                               y=results[2],
                               mode="lines+markers",
                               name="max")
            data = [minTrace, meanTrace, maxTrace]

            layout = Layout(
                title="Buckets Experiment for {} ('{}' concatenation) ".format(
                    modelName, comboMethod),
                xaxis=XAxis(title="Number of samples queried",
                            titlefont=Font(family='Courier New, monospace',
                                           size=18,
                                           color='#7f7f7f'),
                            dtick=1),
                yaxis=YAxis(title=metricName,
                            titlefont=Font(family='Courier New, monospace',
                                           size=18,
                                           color='#7f7f7f')))

            fig = Figure(data=data, layout=layout)
            plotUrl = py.plot(fig)
            print "Plot URL for {}: {}".format(metricName, plotUrl)
示例#29
0
def draw_graph(word, hypernym=False):
    """Draw graph of word hyponym, or hypernym if hypernym=True,
    Displays in Jupyter notebook.
    Requires pre-installed plotly apikey"""
    G = visualize_word(word, not hypernym)
    nxpos = nx.fruchterman_reingold_layout(G)
    labels = []
    pos = []
    for k, v in nxpos.items():
        labels.append(str(k()))
        pos.append(v)
    trace1 = scatter_edges(G, nxpos)
    trace2 = scatter_nodes(pos, labels=labels)

    axis = dict(
        showline=False,  # hide axis line, grid, ticklabels and title
        zeroline=False,
        showgrid=False,
        showticklabels=False,
        title='')
    layout = Layout(
        title='Graph for word "{}"'.format(word),
        font=Font(),
        showlegend=False,
        autosize=True,
        # width=width,
        # height=height,
        xaxis=XAxis(axis),
        yaxis=YAxis(axis),
        #margin=Margin(
        #  l=40,
        #  r=40,
        #  b=85,
        #  t=100,
        #  pad=0,),
        # plot_bgcolor='#EFECEA', #set background color
        hovermode='closest')

    data = Data([trace1, trace2])

    fig = Figure(data=data, layout=layout)
    return plotly.iplot(fig, filename='networkx')
示例#30
0
def make_report_plotly(counts, suffix, report):
    
    for count in counts:
        run_test( report, count )
        
    for category, results in report.iteritems():
        
        #formatter = results['formatter']
        scale = results['scale']
        unit = results['unit']
        
        bars = []
        for name, values in results.iteritems():
            if name in ['title', 'scale', 'unit']:
                continue

            #values = map(formatter, map(lambda x: x * scale, values))
            values = map(lambda x: x * scale, values)

            bar = Bar(  x=counts,
                        y=values,
                        name=name )
            bars.append(bar)
    
        layout = Layout(title=results['title'],
                        font=Font(family='Raleway, sans-serif'),
                        showlegend=True,
                        barmode='group',
                        bargap=0.15,
                        bargroupgap=0.1,
                        legend=Legend(x=0, y=1.0),
                        xaxis=XAxis(title='Num Sites', type='category'),
                        yaxis=YAxis(title=results['unit'])
                        )
        
        data = Data(bars)
        fig = Figure(data=data, layout=layout)
        outpath = '../images/%s%s.png' % (category, suffix)
        py.image.save_as(fig, outpath)
        
        print "Wrote", outpath
def make_XAxis(x_in):
    xaxis = XAxis(range=[x_in.min(),x_in.max()])
    xaxis.update(axis_style)
    return xaxis