Python plotly.plotly.plot() Examples

The following are code examples for showing how to use plotly.plotly.plot(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pymoku   Author: liquidinstruments   File: plotly_support.py    MIT License 6 votes vote down vote up
def plot_frame(dataframe, uname=None, api_key=None, mode='lines', line={}):
    try:
        import plotly.plotly as ply
        from plotly.graph_objs import Scatter, Layout, Data, Figure
    except ImportError:
        raise InvalidOperationException("Please install the Python "
                                        "plotly bindings")

    if uname and api_key:
        ply.sign_in(uname, api_key)

    c1 = dataframe.ch1
    c2 = dataframe.ch2
    x = list(range(len(c1)))

    t1 = Scatter(x=x, y=c1, mode=mode, line=line)
    t2 = Scatter(x=x, y=c2, mode=mode, line=line)

    layout = Layout(title="Moku:Lab Frame Grab")
    data = Data([t1, t2])

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

    return ply.plot(fig) 
Example 2
Project: bitcoin-feemodel-data   Author: bitcoinfees   File: plotwaits.py    MIT License 6 votes vote down vote up
def plotwaits(traces, minheight, maxheight, basedir=BASEDIR):
    title = ("Empirical CDF of waittimes from blocks {}-{}".
             format(minheight, maxheight))
    data = Data(traces)
    layout = Layout(
        title=title,
        yaxis=YAxis(
            title="Empirical CDF",
            range=[0, 1]
        ),
        xaxis=XAxis(
            title="Wait time (s)",
            rangemode="tozero",
            type="log"
        ),
        hovermode="closest"
    )
    fig = Figure(data=data, layout=layout)
    basedir = basedir if basedir.endswith('/') else basedir + '/'
    filename = basedir + "waits_cdf"
    return py.plot(fig, filename=filename, auto_open=False) 
Example 3
Project: Bee_space   Author: hobrien   File: ParseSpec.py    MIT License 6 votes vote down vote up
def GetColours(SpecData, args):
    #print "gettting colours"
    #This will do most of the work of converting a spec reading into values to plot on a 3d plot or hexagon
    BeeSensitivity = GetIntervals(read_csv(args.BeeSensitivityFileName, sep='\t', index_col=False))
    assert len(BeeSensitivity.index) == 81, "Bee Sensitivity dataset only has %i rows. Are all values from 300-700 included?" % len(BeeSensitivity.index)
    Background = GetIntervals(read_csv(args.BackgroundFileName, sep='\t', index_col=False))
    assert len(Background.index) == 81, "Background dataset only has %i rows. Are all values from 300-700 included?" % len(Background.index)
    SpecData.rename(columns={SpecData.columns[1]:'Reflectance'}, inplace=True)
    Combined = merge(merge(BeeSensitivity, Background, on='Wavelength'), SpecData, on='Wavelength')
    U_B_G_Y_X = []
    for colour in ('UV', 'Blue', 'Green'):
        R = 1/sum(Combined[colour]*Combined['Daylight']*Combined['Leaves'])
        raw = sum(Combined[colour]*Combined['Daylight']*Combined['Reflectance'])
        U_B_G_Y_X.append(raw*R/(raw*R+1))
    U_B_G_Y_X.append(U_B_G_Y_X[1]-0.5*(U_B_G_Y_X[0]+U_B_G_Y_X[2]))
    U_B_G_Y_X.append(0.866*(U_B_G_Y_X[2]-U_B_G_Y_X[0]))
    return U_B_G_Y_X 
Example 4
Project: vslam_evaluation   Author: nicolov   File: plot_plotly.py    MIT License 6 votes vote down vote up
def running_times():
    rospack = rospkg.RosPack()
    data_path = os.path.join(rospack.get_path('vslam_evaluation'), 'out')
    df = pd.read_csv(os.path.join(data_path, 'runtimes.txt'),
        header=None,
        index_col=0)

    bars = []

    for col_idx in df:
        this_stack = df[col_idx].dropna()
        bars.append(
            go.Bar(
                x=this_stack.index,
                y=this_stack.values,
                name='Thread {}'.format(col_idx)))

    layout = go.Layout(
        barmode='stack',
        yaxis={'title': 'Running time [s]'})

    fig = go.Figure(data=bars, layout=layout)

    url = py.plot(fig, filename='vslam_eval_run_times') 
Example 5
Project: TwitchStats   Author: dmegahan   File: TwitchGraph.py    Apache License 2.0 6 votes vote down vote up
def createGraphFromJson(self, jsonPath):
        splitPath = jsonPath.split('/')[2:]
        streamer = splitPath[0]
        raw_date = splitPath[2].split('.',1)[0]
        date = splitPath[2].split('.',1)[0].replace('_','/')
        with open(jsonPath) as f:
            data = json.load(f)
            emotes = data['sub emotes']
            x = []
            y = []
            for key, value in emotes.iteritems():
                x.append(key)
                y.append(value)
            data = ([Bar(x=x, y=y)])
            title = streamer + "/J" + raw_date
            logging.info(title + " emote graph created!")
            plot_url = py.plot(data, filename=title, auto_open=False)

#Graph().createGraphFromJson('./data/Destiny/stats/D05_M05_Y2015_H04_m48_s05.json')
#Graph().createGraphFromCSV('./data/destiny/CSV/D05_M05_Y2015_H04_m48_s05.csv') 
Example 6
Project: pyretina   Author: yandexdataschool   File: plot.py    Apache License 2.0 5 votes vote down vote up
def plot_retina_results(predicted, event, max_angle, search_traces = None, against = 'true'):
  thetas, phis, response = event.get_grid()

  m, test, predicted_mapping, test_mapping = binary_metrics(predicted, event, max_angle=max_angle, against = against)
  recognized = predicted_mapping == 1
  test_recognized = test_mapping == 1
  ghost = predicted_mapping == 0
  unrecognized = test_mapping == 0

  plt.figure(figsize=(48, 48))
  plt.contourf(thetas, phis, response, 40, cmap=cm.gist_gray)
  plt.colorbar()

  plt.scatter(predicted[recognized, 0], predicted[recognized, 1], color="green", marker="+",
              label="Recognized (%d)" % np.sum(test_recognized), s=80)

  plt.scatter(test[test_recognized, 0], test[test_recognized, 1], color="green", marker="o",
              s=40)


  plt.scatter(predicted[ghost, 0], predicted[ghost, 1], color="red", marker="x",
              label="Ghost (%d)" % np.sum(ghost), s=80)

  plt.scatter(test[unrecognized, 0], test[unrecognized, 1], color="red", marker="o",
              label="Unrecognized (%d)" % np.sum(unrecognized), s=80)

  if search_traces is not None:
    for trace in search_traces:
      xs = [ p[0] for p in trace ]
      ys = [ p[1] for p in trace ]

      plt.plot(xs, ys, color="blue")

  plt.legend()
  return plt 
Example 7
Project: pyretina   Author: yandexdataschool   File: plot.py    Apache License 2.0 5 votes vote down vote up
def plot_precision_recall(predicted, event, against = 'true', max_angle = 1.0e-2):
  _, precision, recall = precision_recall(predicted, event, against, max_angle)

  plt.figure()
  plt.ylim([0.0, 1.05])
  plt.xlim([0.0, 1.05])
  plt.plot(recall, precision)
  plt.xlabel("Recall")
  plt.ylabel("Precision")

  return plt 
Example 8
Project: LoveIsInTheAir-Stats-Plotter   Author: sahilsareen   File: PieChartPlotter.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, labels, values, username, api_key, plot_name):
        self.logger = logging.getLogger(self.__class__.__name__)
        py.sign_in(username, api_key)
        fig = {
            'data': [{'labels': labels,
                      'values': values,
                      'type': 'pie'}],
            'layout': {'title': "Valentines week - %s #LoveIsInTheAir" % plot_name}
        }
        url = py.plot(fig, filename="Pie Chart %s" % plot_name)
        self.logger.info("Plotted Pie Chart: %s" % url) 
Example 9
Project: UltraSonicSensor_Rpi2   Author: sachinprabhu007   File: ultrasonic_sensor.py    MIT License 5 votes vote down vote up
def plot_graph():
  py.plot(Data([Scatter(x=[],y=[],
                      stream=Stream(token=stream_id,maxpoints=100))]))
   
  #heartbeat(self,reconnect_on=(200, '',408))
  #open(self)
  #write(self,trace,layout=None,Validate=True,reconnect_on=(200, '',408))
  
# -----------------------
# Main Script
# -----------------------

# Use BCM GPIO references
# instead of physical pin numbers 
Example 10
Project: bitcoin-feemodel-data   Author: bitcoinfees   File: plotprofile.py    MIT License 5 votes vote down vote up
def plot_with_retry(fig, filename):
    print(py.plot(fig, filename=filename, auto_open=False)) 
Example 11
Project: bitcoin-feemodel-data   Author: bitcoinfees   File: plotpools.py    MIT License 5 votes vote down vote up
def plot_with_retry(fig, filename):
    print(py.plot(fig, filename=filename, auto_open=False)) 
Example 12
Project: bitcoin-feemodel-data   Author: bitcoinfees   File: plotpvals.py    MIT License 5 votes vote down vote up
def plot_with_retry(fig, filename):
    print(py.plot(fig, filename=filename, auto_open=False)) 
Example 13
Project: bitcoin-feemodel-data   Author: bitcoinfees   File: plotrrd.py    MIT License 5 votes vote down vote up
def rrdplot(times, tracesdata, filename='test'):
    '''Plot based on specified time range.

    starttime/endtime is unix time, interval is the point spacing in seconds.
    '''

    x = [datetime.utcfromtimestamp(t) for t in times]
    traces = [Scatter(x=x, y=tracedata) for tracedata in tracesdata]
    names = ['12 min', '20 min', '30 min', '60 min']
    for i, name in enumerate(names):
        traces[i].update(dict(name=name))
    traces[4].update(dict(
        name='Mempool size',
        xaxis='x2',
        yaxis='y2',
        line=Line(color='black')
    ))
    traces[5].update(dict(
        name='Tx byterate',
        xaxis='x2',
        yaxis='y2',
        line=Line(color='black', dash='dot')
    ))
    traces[6].update(dict(
        name='Capacity byterate',
        xaxis='x2',
        yaxis='y2',
        line=Line(color='black', dash='dash')
    ))
    data = Data(traces)
    fig = Figure(data=data, layout=LAYOUT)
    py.plot(fig, filename=filename, auto_open=False) 
Example 14
Project: JSSP-Genetic-Algorithm   Author: Irvel   File: plotter.py    MIT License 5 votes vote down vote up
def plot(x_data, y_data):
    # x_data = iteration_numbers
    # y_data = makespans
    # colorscale = ['#7A4579', '#D56073', 'rgb(236,158,105)', (1, 1, 0.2), (0.98,0.98,0.98)]
    # fig = FF.create_2D_density(
    #     x_data, y_data, colorscale=colorscale,
    #     hist_color='rgb(255, 237, 222)', point_size=3
    # )

    # py.plot(fig, filename='histogram_subplots')

    # trace = go.Scattergl(
    #     x = x_data,
    #     y = y_data,
    #     mode = 'lines',
    #     marker = dict(
    #         color = 'rgb(152, 0, 0)',
    #         line = dict(
    #             width = 1,
    #             color = 'rgb(0,0,0)')
    #     )
    # )
    # data = [trace]
    # py.plot(data, filename='goodthick')
    plt.plot(x_data, y_data, 'ro')
    plt.title("Initial population: " + str(100) + " Iteration Numbers: " + str(len(x_data)))
    plt.ylabel("Makespan")
    plt.xlabel("Generation")
    plt.show() 
Example 15
Project: ElliotWaveAnalysis   Author: Wkemery   File: Swings.py    GNU General Public License v3.0 5 votes vote down vote up
def graph_OHLC(self):
        #not quite there, but the other one works, which is what i really care about
        OHLC_trace = go.Ohlc(x=self.OHLC_data.Date_Time,
                open=self.OHLC_data.Open,
                high=self.OHLC_data.High,
                low=self.OHLC_data.Low,
                close=self.OHLC_data.Close,
                name="OHLC Data",
                increasing=dict(line=dict(color= '#408e4a')),
                decreasing=dict(line=dict(color= '#cc2718')))

        swing_data = pd.read_csv(self.swing_file, names=['Date_Time', 'Price', 'Direction', 'Row'], parse_dates=True)
        swing_trace = go.Scatter(
            x = swing_data.Date_Time,
            y = swing_data.Price,
            mode = 'lines+markers',
            name = 'Swings',
            line = dict(
                color = ('rgb(111, 126, 130)'),
                width = 3)
        )

        data = [OHLC_trace, swing_trace]
        layout = go.Layout(xaxis = dict(rangeslider = dict(visible = False)), title= self.data_file[:-4])

        fig = go.Figure(data=data, layout=layout)
        py.plot(fig, filename=self.data_file + ".html", output_type='file') 
Example 16
Project: ElliotWaveAnalysis   Author: Wkemery   File: Swings.py    GNU General Public License v3.0 5 votes vote down vote up
def export_OHLC_graph(self):

        if self.update:
            print("Did update, graph is screwy")
        OHLC_trace = go.Ohlc(x=self.OHLC_data.Date_Time,
                open=self.OHLC_data.Open,
                high=self.OHLC_data.High,
                low=self.OHLC_data.Low,
                close=self.OHLC_data.Close,
                name="OHLC Data",
                increasing=dict(line=dict(color= '#408e4a')),
                decreasing=dict(line=dict(color= '#cc2718')))

        swing_data = pd.read_csv(self.swing_file, names=['Date_Time', 'Price', 'Direction', 'Row'], parse_dates=True)
        swing_trace = go.Scatter(
            x = swing_data.Date_Time,
            y = swing_data.Price,
            mode = 'lines+markers',
            name = 'Swings',
            line = dict(
                color = ('rgb(111, 126, 130)'),
                width = 3)
        )

        data = [OHLC_trace, swing_trace]

        layout = {
            'title': self.data_file[:-4],
            'yaxis': {'title': 'Price'},
        }
        fig = go.Figure(data=data, layout=layout)
        offline.plot(fig, output_type='file',filename=self.data_file + ".html", image='png', image_filename=self.data_file) 
Example 17
Project: internetofthings101   Author: TheIoTLearningInitiative   File: main.py    Apache License 2.0 5 votes vote down vote up
def dataPlotlyHandler():

    py.sign_in(username, api_key)

    trace1 = Scatter(
        x=[],
        y=[],
        stream=dict(
            token=stream_token,
            maxpoints=200
        )
    )

    layout = Layout(
        title='Hello Internet of Things 101 Data'
    )

    fig = Figure(data=[trace1], layout=layout)

    print py.plot(fig, filename='Hello Internet of Things 101 Plotly')

    i = 0
    stream = py.Stream(stream_token)
    stream.open()

    while True:
        stream_data = dataPlotly()
        stream.write({'x': i, 'y': stream_data})
        i += 1
        time.sleep(0.25) 
Example 18
Project: internetofthings101   Author: TheIoTLearningInitiative   File: climate.py    Apache License 2.0 5 votes vote down vote up
def graph(self):

        stream_temperature = Scatter(
            x=[],
            y=[],
            stream=dict(
                token=self.streamtoken,
            )
        )

        layout = Layout(
            title="IoTPy Climate"
        )

        this = Figure(data=[stream_temperature], layout=layout)
        py.plot(this, filename='IotPy Climate', auto_open=False)

        stream = py.Stream(self.streamtoken)
        stream.open()
        time.sleep(5)

        counter = 0

        while True:
            temperaturedata = self.bpta.getTemperature()
            stream.write({'x': counter, 'y': temperaturedata})
            counter += 1
            time.sleep(0.25)

# End of File 
Example 19
Project: internetofthings101   Author: TheIoTLearningInitiative   File: randomizer.py    Apache License 2.0 5 votes vote down vote up
def graph(self):

        stream_randomizer = Scatter(
            x=[],
            y=[],
            stream=dict(
                token=self.streamtoken,
            )
        )

        layout = Layout(
            title="IoTPy Randomizer"
        )

        this = Figure(data=[stream_randomizer], layout=layout)
        py.plot(this, filename='IotPy Randomizer', auto_open=False)

        stream = py.Stream(self.streamtoken)
        stream.open()
        time.sleep(5)

        counter = 0

        while True:
            randomizerdata = randint(0,100)
            stream.write({'x': counter, 'y': randomizerdata})
            counter += 1
            time.sleep(0.25)

# End of File 
Example 20
Project: evologger   Author: freeranger   File: __init__.py    MIT License 5 votes vote down vote up
def create_plots():
    # We make a plot for every room
    plotly_logger.info('max points per graph: %s', ploty_max_points_per_graph)
    for zone in zones:
        plotly_logger.info('Creating graph for: %s' % zone)
        stream_id = zones[zone]
        stream = Stream(
            token=stream_id,
            maxpoints=ploty_max_points_per_graph
        )
        trace1 = Scatter(
            x=[],
            y=[],
            mode='lines+markers',
            line=Line(
                shape='spline'
            ),
            stream=stream
        )

        data = Data([trace1])
        layout = Layout(title=zone)
        fig = Figure(data=data, layout=layout)
        py.plot(fig, filename=zone, fileopt='extend')


# if called directly then this is what will execute
# It will create the initial plot.ly reports if need be. 
Example 21
Project: footballpitchplot   Author: olalidmark   File: plotter.py    MIT License 5 votes vote down vote up
def plot(self):
        fig = Figure(data=self.traces, layout=self.layout)
        unique_url = py.plot(fig) 
Example 22
Project: Bee_space   Author: hobrien   File: ParseSpec.py    MIT License 5 votes vote down vote up
def Plotly(colours):
    from plotly.plotly import plot
    from plotly.graph_objs import Scatter3d, Layout, XAxis, YAxis, ZAxis, Scene, Figure
    
    traces = []
    for sample_id in colours['x'].keys():
        traces.append(Scatter3d(x=colours['b'][sample_id], y=colours['g'][sample_id], z=colours['uv'][sample_id], mode='markers', name=sample_id))

    layout = Layout(
        showlegend=True,
        autosize=True,
        width=933,
        height=868,
        xaxis=XAxis(type='linear'),
        yaxis=YAxis(type='linear'),
        dragmode='rotate',
        barmode='group',
        scene=Scene(
            xaxis=XAxis(
                title='Blue',
                range=[0, 1],
                type='linear',
                autorange=False
            ),
            yaxis=YAxis(
                title='Green',
                range=[0, 1],
                type='linear',
                autorange=False
            ),
            zaxis=ZAxis(
                title='UV',
                range=[0, 1],
                type='linear',
                autorange=False
            ),
            cameraposition=[[0.6702282428741455, 0.49358895421028137, -0.5526835918426514, 0.041290637105703354], [0, 0, 0], 2.8476730120752833]
        )
    )
    fig = Figure(data=traces)
    plot_url = plot(fig) 
Example 23
Project: Bee_space   Author: hobrien   File: ParseSpec.py    MIT License 5 votes vote down vote up
def parse_args(input):
  import argparse
  parser = argparse.ArgumentParser(description="Calculate bee colour perception from spec data and plot in 2 or 3 dimensions.\nWavelengths must be in first column. Spec readings must be in all other columns")
  parser.add_argument('--outfile', '-o', dest='outfile', default='',
                   help='Output file name')
  parser.add_argument('--mode', '-m', choices=['hexagon', 'text', 'plotly', 'rotate'], default = 'hexagon',
                   help='Output mode (colour hexagon, text file with coordinates, plotly or rotating gif)')
  parser.add_argument('--background', '-b', dest='BackgroundFileName', 
                   default=os.path.join(os.path.split(os.path.split(os.path.realpath(sys.argv[0]))[0])[0],'Data', 'Background.txt'), 
                   type=str, help='Location of background reflectance data')  
  parser.add_argument('--sensitivity', '-s', dest='BeeSensitivityFileName', 
                   default=os.path.join(os.path.split(os.path.split(os.path.realpath(sys.argv[0]))[0])[0],'Data', 'BeeSensitivity.txt'), 
                   type=str, help='Location of bee spectral sensitivity data')  
  parser.add_argument('--resolution', '-r', dest='resolution', default=50, type=int,
                   help='GIF resolution (DPI) for rotating plots. Note that file size can get very large if this is increased from 50')  
  parser.add_argument('--delimiter', '-d',  choices=['Tab', 'Comma', 'Space'], 
                   default = 'Tab', dest='sep', help='column separator')
  parser.add_argument('--column_headers', '-c', action="store_true",
                   help='Files have header rows')  
  parser.add_argument('--version', '-v', action='version', version='%(prog)s 1.0')
  parser.add_argument('infiles', nargs='+')
  args = parser.parse_args(input)
  if args.sep == 'Tab':
      args.sep = '\t'
  elif args.sep == 'Comma':
      args.sep = ','
  else:    
      args.sep = ' ' 
  return args 
Example 24
Project: vslam_evaluation   Author: nicolov   File: plot_plotly.py    MIT License 5 votes vote down vote up
def position_comparison():
    plot_layout = go.Layout(
        title='X position comparison',
        xaxis={'title': 'Time [s]'},
        yaxis={'title': 'X position [m]'}
    )

    plot_data = []

    for i, (label, bag_file_name, odometry_topic_name) in enumerate(comparisons):
        td_visual, td_vicon = load_one_comparison(bag_file_name, odometry_topic_name)

        plot_data.append(
            go.Scatter(x=td_visual.col(0)[::4],
                y=td_visual.col(1)[::4],
                mode='lines+markers',
                name=label,
                marker={'maxdisplayed': 150}))

        if i == 0:
            # Only plot ground truth once
            plot_data.append(
                go.Scatter(x=td_vicon.col(0)[::20],
                    y=td_vicon.col(1)[::20],
                    mode='lines+markers',
                    name='Truth',
                    marker={'maxdisplayed': 150}))

    fig = go.Figure(data=plot_data, layout=plot_layout)
    url = py.plot(fig, filename='vslam_eval_x_pos') 
Example 25
Project: rising_block   Author: eddyzerotoappstore   File: candle_stick.py    GNU General Public License v3.0 5 votes vote down vote up
def analyze(context, perf):
    trace0 = go.Ohlc(x=perf.index.to_series(),
                     open=perf.open,
                     high=perf.high,
                     low=perf.low,
                     close=perf.close,
                     showlegend=False)

    pos_values = perf.signal[perf.signal > 0]
    pos_high_values = perf.high[perf.high.index.isin(pos_values.index)]
    neg_values = perf.signal[perf.signal < 0]
    neg_low_values = perf.high[perf.high.index.isin(neg_values.index)]

    trace1 = go.Scatter(
        x=pos_values.index.to_series(),
        y=pos_high_values,
        mode='markers',
        name='Bull Break'
    )

    trace2 = go.Scatter(
        x=neg_values.index.to_series(),
        y=neg_low_values,
        mode='markers',
        name='Bear Break'
    )

    data = [trace0, trace1, trace2]
    py.plot(data, filename='simple_ohlc2') 
Example 26
Project: memgraph   Author: baranbartu   File: plot.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def make_plot(logs, file_name):
    tls.set_credentials_file(username='memgraph',
                                      api_key='wb1kstdv2f')
    x = [line['x'] for line in sorted(logs, key=lambda l: l['x'])]
    y = [line['y'] for line in sorted(logs, key=lambda l: l['x'])]
    trace = go.Scatter(
        x=x,
        y=y
    )
    data = [trace]

    plot_url = py.plot(data, filename=file_name, share='public')
    logger.info('Please visit this url: %s', plot_url) 
Example 27
Project: Outsider   Author: Reticulatas   File: Outsider.py    MIT License 5 votes vote down vote up
def plot(self):
        x = range(0,max_samples%graph_density)
        y = self.prices[::graph_density]
        trace = Scatter(x=x,y=y)
        data = Data([trace])
        plot_url = py.plot(data, filename=self.code)
        print plot_url
        return 
Example 28
Project: CombinX   Author: SimCMinMax   File: plot.py    GNU General Public License v3.0 4 votes vote down vote up
def generatePlot(trace, traceLabels, plotname):
    data = [trace, traceLabels]
    layout = go.Layout(
        margin=dict(
            l=0,
            r=0,
            b=0,
            t=32,
        ),
        title=plotname,
        scene=dict(
            xaxis=dict(
                showgrid=False,
                showticklabels=False,
                showspikes=False,
                showline=False,
                showaxeslabels=False,
                zeroline=False,
                title='',
            ),
            yaxis=dict(
                showgrid=False,
                showticklabels=False,
                showspikes=False,
                showline=False,
                showaxeslabels=False,
                zeroline=False,
                title='',
            ),
            zaxis=dict(
                showgrid=False,
                showticklabels=False,
                showspikes=False,
                showline=False,
                showaxeslabels=False,
                zeroline=False,
                title='',
            ),
        )
    )
    fig = go.Figure(data=data, layout=layout)
    return py.plot(fig, filename=plotname, auto_open=False) 
Example 29
Project: pyretina   Author: yandexdataschool   File: plot.py    Apache License 2.0 4 votes vote down vote up
def plot_event_plotly(event, tracks, unrecognized_tracks=None, filename="retina"):
  import plotly.graph_objs as go
  import plotly.tools as tls
  import plotly.plotly as py

  def with_return_to_origin(t):
      t1 = np.zeros(t.shape[0] * 2)
      t1[1::2] = t
      return t1

  hits_3d = go.Scatter3d(
      x = event[:, 2],
      y = event[:, 0],
      z = event[:, 1],
      mode = "markers",
      marker = {"size" : 3.0}
  )

  tracks_3d = go.Scatter3d (
      x = with_return_to_origin(tracks[:, 2]),  # x coords
      y = with_return_to_origin(tracks[:, 0]),  # y coords
      z = with_return_to_origin(tracks[:, 1]),  # z coords
      mode = 'lines',      # (!) draw lines between coords (as in Scatter)
      line = dict(
          color = "green",
          width=2
        )
  )

  # tracks_unrecognised_3d = go.Scatter3d (
  #     x = with_return_to_origin(unrecognized_tracks[:, 2]),  # x coords
  #     y = with_return_to_origin(unrecognized_tracks[:, 0]),  # y coords
  #     z = with_return_to_origin(unrecognized_tracks[:, 1]),  # z coords
  #     mode = 'lines',      # (!) draw lines between coords (as in Scatter)
  #     line = dict(
  #         color = "red",
  #         width=2
  #       )
  # )

  data=[hits_3d, tracks_3d]

  box = mininal_sq(event)

  layout = go.Layout (
    title="Retina"
    # scene = go.Scene(
    #   xaxis=dict(range=box[0]),
    #   yaxis=dict(range=box[1]),
    #   zaxis=dict(range=box[2])
    # )
  )

  fig = go.Figure(data=data, layout=layout)
  py.plot(fig)

  return fig 
Example 30
Project: internetofthings101   Author: TheIoTLearningInitiative   File: system.py    Apache License 2.0 4 votes vote down vote up
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()

# End of File 
Example 31
Project: tempmon   Author: dhellmann   File: daemon.py    Apache License 2.0 4 votes vote down vote up
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 
Example 32
Project: SIH2019   Author: adityaprakash-bobby   File: map.py    GNU General Public License v3.0 4 votes vote down vote up
def printmap():
    mapbox_access_token = 'pk.eyJ1IjoiYWRpdHlhMDk4NzY1NDMyMSIsImEiOiJjanNzbHZsNDcxb3A1NDlvNHdqa2lkbDhtIn0.bxa2ewJsYTyW_NJcShlPbw'

    df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/Nuclear%20Waste%20Sites%20on%20American%20Campuses.csv')
    site_lat = df.lat
    site_lon = df.lon
    locations_name = df.text

    data = [
        go.Scattermapbox(
            lat=site_lat,
            lon=site_lon,
            mode='markers',
            marker=dict(
                size=17,
                color='rgb(255, 0, 0)',
                opacity=0.7
            ),
            text=locations_name,
            hoverinfo='text'
        ),
        go.Scattermapbox(
            lat=site_lat,
            lon=site_lon,
            mode='markers',
            marker=dict(
                size=8,
                color='rgb(242, 177, 172)',
                opacity=0.7
            ),
            hoverinfo='none'
        )]
            
    layout = go.Layout(
        title='Sales of products',
        autosize=True,
        hovermode='closest',
        showlegend=False,
        mapbox=dict(
            accesstoken=mapbox_access_token,
            bearing=0,
            center=dict(
                lat=38,
                lon=-94
            ),
            pitch=0,
            zoom=3,
            style='light'
        ),
    )

    fig = dict(data=data, layout=layout)
    plotmap = py.plot(fig, filename='Nuclear Waste Sites on American Campuses', auto_open=False)
    return plotmap 
Example 33
Project: TwitchStats   Author: dmegahan   File: TwitchGraph.py    Apache License 2.0 4 votes vote down vote up
def createGraphFromCSV(self, csvPath):
        #split the file path to get the stream name from the folder structure we use
        splitPath = csvPath.split('/')[2:]
        streamer = splitPath[0]
        #get the date from the filename
        raw_date = splitPath[2].split('.',1)[0]
        #date = splitPath[2].split('.',1)[0].replace('_','/')
        with open(csvPath, 'rb') as csvfile:
            reader = csv.reader(csvfile)
            x_points = []
            y_points = []
            last_viewer_count = -1
            current_game_played = "Stream Started!"
            #games_graph is a list of scatter plots, each scatter plot being the views for a
            #different game
            games_graph = []
            for row in reader:
                #add row as a data point to graph
                #check for change in game
                if row[1] != current_game_played:
                    games_graph.append(Scatter(x=x_points, y=y_points,
                                               mode='lines',
                                               name=current_game_played))
                    current_game_played = row[1]
                    #clear the points lists, because we need to seperate the view nums for
                    #different games
                    #add the last point from last Scatter graph to new set of points, so that the graph is connected
                    last_x = x_points[-1:]
                    last_y = y_points[-1:]
                    x_points = [last_x]
                    y_points = [last_y]

                #need to check if viewer number is same as last point added
                #API doesnt constantly update viewer num,
                if row[0] != last_viewer_count:
                    last_viewer_count = row[0]
                    date = datetime.datetime.strptime(row[2], self.config["DATE_TIME_FORMAT"])
                    time = date.time()
                    x_points.append(time)
                    y_points.append(row[0])

            title = streamer + "/" + raw_date
            layout = Layout(title=title,xaxis=XAxis(title='Time'),
                            yaxis=YAxis(title='Viewers'),
                            showlegend=True)

            data = Data(games_graph[1:])
            fig = Figure(data=data,layout=layout)
            print title + "created!"
            logging.info(title + " viewer graph created!")
            plot_url = py.plot(fig,filename=title, auto_open=False)

    #create a basic bar graph based on the emotes used during the stream 
Example 34
Project: dbling   Author: sefcom   File: plot_centroids.py    MIT License 4 votes vote down vote up
def diff1(self):
        point_data = {}  # Keys: distances, Values: list of extension IDs
        baseline_row = None
        baseline_id = None

        # Iterate through the rows
        for row in self.db_conn.execute(select([self.extension])):
            # Get the centroid
            centroid = ()
            for field in self.all_fields:
                col = getattr(self.extension.c, USED_TO_DB[field])
                centroid += (row[col],)

            if baseline_row is None:
                baseline_row = centroid
                baseline_id = row[self.extension.c.ext_id]
                continue

            diff = centroid_difference(baseline_row, centroid, self.norm_tup)
            try:
                point_data[diff].append(row[self.extension.c.ext_id])
            except KeyError:
                point_data[diff] = [row[self.extension.c.ext_id]]

        diffs = list(point_data.keys())
        diffs.sort()
        y = []
        text = []
        for r in diffs:
            for p in point_data[r]:
                y.append(r)
                text.append(p)

        trace = Scatter(
            y=y[:40000],
            text=text[:40000],
            name='Diff against %s' % baseline_id,
            mode='markers',
            marker=Marker(size=3)
        )

        data = Data([trace])
        if OFFLINE:
            pyoff.plot(data)
        else:
            plot_url = py.plot(data, filename="centroid-distances-normalized")
            print("Plot ready at: %s" % plot_url) 
Example 35
Project: dbling   Author: sefcom   File: plot_centroids.py    MIT License 4 votes vote down vote up
def hist(self):
        ids_calculated = []
        centroid_counts = []
        key_field = USED_TO_DB[self.all_fields[0]]

        # Iterate through the rows
        for row in self.db_conn.execute(select([self.extension])):
            # Skip if we've already seen this row
            if row[self.extension.c.ext_id] in ids_calculated:
                continue
            ids_calculated.append(row[self.extension.c.ext_id])
            same_centroid = 1

            # Get the centroid
            centroid = ()
            for field in self.all_fields:
                col = getattr(self.extension.c, USED_TO_DB[field])
                centroid += (row[col],)

            # Do some really inefficient coding...
            result = self.db_conn.execute(select([self.extension]).
                                          where((getattr(self.extension.c, key_field)) == row[key_field]))
            for other_row in result:
                # Get the other centroid
                other_centroid = ()
                for field in self.all_fields:
                    col = getattr(self.extension.c, USED_TO_DB[field])
                    other_centroid += (other_row[col],)

                # Calculate the difference between the two vectors
                diff = centroid_difference(centroid, other_centroid, self.norm_tup)
                if diff == 0:
                    same_centroid += 1
                    ids_calculated.append(other_row[self.extension.c.ext_id])
            centroid_counts.append(same_centroid)

        # Create the histogram
        data = Data([Histogram(x=centroid_counts)])
        if OFFLINE:
            pyoff.plot(data)
        else:
            plot_url = py.plot(data, filename="centroid-cluster-histogram")
            print("Plot ready at: %s" % plot_url) 
Example 36
Project: dbling   Author: sefcom   File: gripper.py    MIT License 4 votes vote down vote up
def main(**kwargs):

    levels = ('dy', 'sg', 'hr')
    if kwargs['--level'] not in levels:
        raise ValueError('Specified level must be one of {}'.format(levels))

    what = []
    if kwargs['created']:
        what.append('created')
    if kwargs['revised']:
        what.append('revisions')
    if kwargs['comment']:
        what.append('comments')

    if kwargs.get('drive'):
        api, title = 'drive', 'User Activity on Google Drive'
    elif kwargs.get('reports'):
        api, title = 'reports', 'Something Awesome'
    else:
        # This should never happen since docopt validates commands for us
        raise ValueError('No known command given')

    args = dict(
        api=api,
        impersonated_user_email=kwargs['--email'],
        start=kwargs['--start'],
        end=kwargs['--end'],
        timezone=kwargs['--tz'],
    )
    api_obj = get_api(**args)
    data = api_obj.activity(use_cached=kwargs['--cached'], what=what, level=kwargs['--level'])
    fig = heatmap(title=title, **data)

    plot_args = {
        'figure_or_data': fig,
        'filename': '{}-activity-heatmap'.format(api),
    }
    try:
        __IPYTHON__
    except NameError:
        url = py.plot(**plot_args)
        print('The plotted figure is now available at:\n{}\n'.format(url))
    else:
        py.iplot(**plot_args)