Exemple #1
0
def _set_axis(self,traces,on=None,side='right',title=''):
	"""
	Sets the axis in which each trace should appear
	If the axis doesn't exist then a new axis is created

	Parameters:
	-----------
		traces : list(str)
			List of trace names 
		on : string
			The axis in which the traces should be placed. 
			If this is not indicated then a new axis will be
			created
		side : string
			Side where the axis will be placed
				'left'
				'right'
		title : string
			Sets the title of the axis
			Applies only to new axis
	"""
	fig=Figure(self.copy())
	if not isinstance(traces,list):
		traces=[traces]

	def update_data(trace,y):
		anchor=fig.axis['def'][y]['anchor'] if 'anchor' in fig.axis['def'][y] else 'x1'
		idx=fig.trace_dict[trace] if isinstance(trace,str) else trace
		fig['data'][idx]['xaxis']=anchor
		fig['data'][idx]['yaxis']=y

	for trace in traces:
		if on:
			if on not in fig.axis['def']:
				raise Exception('"on" axis does not exists: {0}'.format(on))
			update_data(trace,y=on)
		else:
			curr_x,curr_y=fig.axis['ref'][trace]
			domain='[0.0, 1.0]' if 'domain' not in fig.axis['def'][curr_y] else str(fig.axis['def'][curr_y]['domain'])
			try:
				new_axis=fig.axis['dom']['y'][domain][side]
			except KeyError:
				axis=YAxis(fig.axis['def'][curr_y].copy())
				### check overlaying values
				axis.update(title=title,overlaying=curr_y,side=side,anchor=curr_x)
				axis_idx=str(fig.axis['len']['y']+1)
				fig['layout']['yaxis{0}'.format(axis_idx)]=axis
				new_axis='y{0}'.format(axis_idx)
			update_data(trace,y=new_axis)


	for k in fig.axis['def'].keys():
		id='{0}axis{1}'.format(k[0],k[-1:])
		if k not in fig.axis['ref_axis']:
			try:
				del fig['layout'][id]
			except KeyError:
				pass

	return fig
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)
Exemple #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
def dataPlotlyHandler():

    configuration = ConfigParser.ConfigParser()
    configuration.read('credentials.config')
    username = configuration.get('plotly', 'username')
    apikey = configuration.get('plotly', 'apikey')
    streamtokentx = configuration.get('plotly', 'streamtokentx')
    streamtokenrx = configuration.get('plotly', 'streamtokenrx')

    py.sign_in(username, apikey)

    trace_network_tx = Scatter(x=[],
                               y=[],
                               stream=Stream(token=streamtokentx, ),
                               yaxis='tx')

    trace_network_rx = Scatter(x=[],
                               y=[],
                               stream=Stream(token=streamtokenrx, ),
                               yaxis='rx')

    layout = Layout(title='IoT Lab Network Health System',
                    yaxis=YAxis(title='Bytes'),
                    yaxis2=YAxis(title='%', side='right', overlaying="y"))

    data = Data([trace_network_tx, trace_network_rx])
    fig = Figure(data=data, layout=layout)

    print py.plot(fig,
                  filename='IoT Lab Network Health System',
                  auto_open=False)

    stream_network_tx = py.Stream(streamtokentx)
    stream_network_tx.open()

    stream_network_rx = py.Stream(streamtokenrx)
    stream_network_rx.open()

    counter = 0

    while True:
        output = psutil.net_io_counters()
        randoma = randint(0, 1000)
        randomb = randint(0, 1000)
        stream_network_tx.write({'x': counter, 'y': randoma})
        stream_network_rx.write({'x': counter, 'y': randomb})
        counter += 1
        time.sleep(0.25)

    stream_network_tx.close()
    stream_network_rx.close()
Exemple #5
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 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',
                            },}]
                   )
    ))
Exemple #7
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
Exemple #8
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)
Exemple #9
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)
Exemple #10
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)
Exemple #11
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)
Exemple #12
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!"
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)
Exemple #14
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)
Exemple #15
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
Exemple #16
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)
Exemple #17
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
Exemple #18
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)
Exemple #19
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)
Exemple #20
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)
Exemple #21
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)))
    def graph(self):

        trace_network_tx = Scatter(x=[],
                                   y=[],
                                   stream=Stream(token=self.streamtokentx, ),
                                   yaxis='tx')

        trace_network_rx = Scatter(x=[],
                                   y=[],
                                   stream=Stream(token=self.streamtokenrx, ),
                                   yaxis='rx')

        layout = Layout(title='IoTPy Network Health System',
                        yaxis=YAxis(title='Bytes'),
                        yaxis2=YAxis(title='%', side='right', overlaying="y"))

        data = Data([trace_network_tx, trace_network_rx])
        fig = Figure(data=data, layout=layout)

        print py.plot(fig,
                      filename='IoTPy Network Health System',
                      auto_open=False)

        stream_network_tx = py.Stream(self.streamtokentx)
        stream_network_tx.open()

        stream_network_rx = py.Stream(self.streamtokenrx)
        stream_network_rx.open()
        time.sleep(5)

        counter = 0

        while True:
            output = psutil.net_io_counters()
            print "Network Bytes Tx %s" % output.bytes_sent
            print "Network Bytes Rx %s" % output.bytes_recv
            stream_network_tx.write({'x': counter, 'y': output.bytes_sent})
            stream_network_rx.write({'x': counter, 'y': output.bytes_recv})
            counter += 1
            time.sleep(0.25)

        stream_network_tx.close()
        stream_network_rx.close()
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)
Exemple #24
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
                 ),
                 yaxis2=YAxis(
                   overlaying="y",
                   side="right"
                 ),
                 barmode="stack",
                 bargap=0)
Exemple #25
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
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
Exemple #27
0
def create_plot(username, api_key,
                weather_token,
                sensor_tokens, sensor_names,
                title, units,
                max_points):
    py.sign_in(username, api_key)
    traces = [
        Scatter(
            x=[],
            y=[],
            name=n,
            stream={
                'token': t,
                # 'maxpoints': max_points,
            }
        )
        for t, n in zip(sensor_tokens, sensor_names)
    ]
    traces.append(
        Scatter(
            x=[],
            y=[],
            name='Outside Temperature',
            stream={
                'token': weather_token,
                # 'maxpoints': max_points,
            }
        )
    )
    layout = Layout(
        title=title,
        yaxis=YAxis(
            title='Degrees %s' % units.title(),
        ),
        showlegend=True,
    )
    fig = Figure(data=traces, layout=layout)
    plot_url = py.plot(fig, filename=title, extend=True, auto_open=False)
    LOG.info('Output graph visible at %s', plot_url)

    sensor_streams = {
        t: py.Stream(t)
        for t in sensor_tokens
    }
    for s in sensor_streams.values():
        s.open()

    weather_stream = py.Stream(weather_token)
    weather_stream.open()

    return sensor_streams, weather_stream
Exemple #28
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')
Exemple #30
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'))
    })
Exemple #31
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 make_YAxis(y_in):
    yaxis = YAxis(range=[y_in.min(),y_in.max()])
    yaxis.update(axis_style)
    return yaxis