コード例 #1
0
def getPlot(y, symbol, dash, ytitle):
    return Scatter(
        **{
            "x": x,
            "y": y,
            "name": ytitle,
            "marker": {
                "symbol": symbol,
                "size": 10,
            },
            "line": {
                "dash": dash,
                "color": "black",
            },
        })
コード例 #2
0
ファイル: stats.py プロジェクト: zjhuntin/stat-tracker
def show_stats(id):
    form = UpdateForm()
    activity = Activity.query.filter(Activity.id == id).first()
    stat_data = Stat.query.filter(Stat.activity_id == activity.id).order_by(
        Stat.when.desc())
    dates = [date.when.strftime("%b %d") for date in stat_data]
    occurrences = [stat.occurrences for stat in stat_data]
    stat_chart = Scatter(x=dates, y=occurrences)
    data = Data([stat_chart])
    chart_url = py.plot(data, auto_open=False)
    return render_template('show_stats.html',
                           activity=activity,
                           chart_url=chart_url,
                           form=form,
                           stats=stat_data)
コード例 #3
0
def get_trace_from_baseline_data(data, lgd_name, shw_lgd, colours):
    t1_min, t1_lower, t1_mean, t1_upper, t1_max = get_trace_data(data)
    # get the actual "trace" for plotly

    trace1_min = Scatter(x=time_scale,
                         y=t1_min,
                         line=Line(color=colours[1], dash='dash'),
                         name='Min')
    trace1_lower = Scatter(x=time_scale,
                           y=t1_lower,
                           line=Line(color=transparent),
                           name='UpperStdDev',
                           showlegend=False)
    trace1_mean = Scatter(x=time_scale,
                          y=t1_mean,
                          fill='tonexty',
                          fillcolor=colours[1],
                          line=Line(color=colours[0]),
                          name=lgd_name,
                          showlegend=shw_lgd,
                          orientation="h")
    trace1_upper = Scatter(x=time_scale,
                           y=t1_upper,
                           fill='tonexty',
                           fillcolor=colours[1],
                           line=Line(color=transparent),
                           name='LowerStdDev',
                           showlegend=False)
    trace1_max = Scatter(x=time_scale,
                         y=t1_max,
                         line=Line(color=colours[1], dash='dash'),
                         name='Max')

    return [
        trace1_lower, trace1_mean, trace1_upper
    ]  # [trace1_min, trace1_lower, trace1_mean, trace1_upper, trace1_max]
def setup():
    py.sign_in(username, api_key)
    trace1 = Scatter(x=[],
                     y=[],
                     stream=dict(token=stream_token, maxpoints=200))
    layout = Layout(
        title=
        'Raspberry Pi Streaming LM35 temperature sensor data through MCP3002 ADC'
    )
    fig = Figure(data=[trace1], layout=layout)
    print py.plot(
        fig,
        filename=
        'Raspberry Pi Streaming LM35 temperature sensor data through MCP3002 ADC'
    )
コード例 #5
0
ファイル: plotshwfs.py プロジェクト: joamatab/soapytest
def plotSHPixelScale(outputdir=None):
    if outputdir is None:
        outputdir = os.path.join(SOAPYTEST_DIR, "plots/")
    print("\nPLOT SH WFS PIXELSCALE\n***")
    ps, mps = wfs.shpixelscale.testPixelScale()

    filename = os.path.join(outputdir, 'shpixelscale.html')
    plotly.offline.plot(
        {
            "data": [
                Scatter(x=ps, y=mps, name="Soapy Pixel Scale"),
                Scatter(x=ps,
                        y=ps,
                        name='Theoretical',
                        line={
                            'dash': 'dash',
                            'color': 'black'
                        })
            ],
            "layout":
            Layout(title='Pixel Scale', legend={'x': 0})
        },
        auto_open=False,
        filename=filename)
コード例 #6
0
ファイル: utils.py プロジェクト: zhexiaozhe/ACER
def plot_line(xs, ys_population):
  max_colour = 'rgb(0, 132, 180)'
  mean_colour = 'rgb(0, 172, 237)'
  std_colour = 'rgba(29, 202, 255, 0.2)'

  ys = torch.Tensor(ys_population)
  ys_min = ys.min(1)[0].squeeze()
  ys_max = ys.max(1)[0].squeeze()
  ys_mean = ys.mean(1).squeeze()
  ys_std = ys.std(1).squeeze()
  ys_upper, ys_lower = ys_mean + ys_std, ys_mean - ys_std

  trace_max = Scatter(x=xs, y=ys_max.numpy(), line=Line(color=max_colour, dash='dash'), name='Max')
  trace_upper = Scatter(x=xs, y=ys_upper.numpy(), line=Line(color='transparent'), name='+1 Std. Dev.', showlegend=False)
  trace_mean = Scatter(x=xs, y=ys_mean.numpy(), fill='tonexty', fillcolor=std_colour, line=Line(color=mean_colour), name='Mean')
  trace_lower = Scatter(x=xs, y=ys_lower.numpy(), fill='tonexty', fillcolor=std_colour, line=Line(color='transparent'), name='-1 Std. Dev.', showlegend=False)
  trace_min = Scatter(x=xs, y=ys_min.numpy(), line=Line(color=max_colour, dash='dash'), name='Min')

  plotly.offline.plot({
    'data': [trace_upper, trace_mean, trace_lower, trace_min, trace_max],
    'layout': dict(title='Rewards',
                   xaxis={'title': 'Step'},
                   yaxis={'title': 'Average Reward'})
  }, filename='rewards.html', auto_open=False)
コード例 #7
0
    def build(self, x, y, title=""):
        div = plotly.offline.plot(
            {
                "data": [Scatter(x=x, y=y)],
                "layout":
                Layout(
                    title=title,
                    # xaxis=dict(range=[4200, 5300]),
                    # yaxis=dict(range=[0.5, 2]),
                )
            },
            output_type='div',
            include_plotlyjs=False)

        return div
コード例 #8
0
ファイル: cron.py プロジェクト: BartoszMakowski/sw-monitoring
def generate_plot(node_name, sensor_name, delta=datetime.timedelta(hours=24), suffix='24h', path='static/plots/'):
    x = []
    y = []

    for record in session.query(Measurement).filter(Measurement.node == node_name). \
            filter(Measurement.sensor == sensor_name). \
            filter(Measurement.time > datetime.date.today() - delta).all():
        print(record.value)
        x.append(record.time)
        y.append(record.value)

    plotly.offline.plot({
        "data": [Scatter(x=x, y=y)],
        "layout": Layout(title=str(node_name + ': ' + sensor_name + ' - ' + suffix)),
    }, filename=str(path + node_name + '_' + sensor_name + '_' + suffix + '.html'))
コード例 #9
0
ファイル: plotting.py プロジェクト: WGierke/OSIMAB
def get_labels_scatter(data_df, labels_df, value_key):
    anomaly_indices = labels_df[labels_df[value_key] > 0].index
    return Scatter(x=anomaly_indices,
                   y=[
                       data_df.loc[index,
                                   value_key] if index in data_df.index else 0
                       for index in anomaly_indices
                   ],
                   mode="markers",
                   name="Anomaly",
                   text=["Anomalous Instance"],
                   marker=Marker(color="rgb(20, 200, 20)",
                                 size=15.0,
                                 symbol='diamond',
                                 line=Line(color="rgb(20, 200, 20)", width=2)))
コード例 #10
0
ファイル: plot_definitions.py プロジェクト: vlad17/GPy
 def show_canvas(self, canvas, filename=None, **kwargs):
     figure, _, _ = canvas
     if len(figure.data) == 0:
         # add mock data
         figure.append_trace(Scatter(x=[], y=[], name='', showlegend=False),
                             1, 1)
     from ..gpy_plot.plot_util import in_ipynb
     if in_ipynb():
         return py.iplot(
             figure, filename=filename
         )  #self.current_states[hex(id(figure))]['filename'])
     else:
         return py.plot(
             figure, filename=filename
         )  #self.current_states[hex(id(figure))]['filename'])
コード例 #11
0
    def plot_regret_alpha(self) -> None:
        """Plot Regret in model selection of CFCV with varying values of alpha."""
        regret = np.mean(self.regret_alpha, 0)
        upper = regret + np.std(self.regret_alpha, 0) / np.sqrt(self.iters)
        lower = regret - np.std(self.regret_alpha, 0) / np.sqrt(self.iters)

        scatter_list = [
            Scatter(x=self.alpha_list,
                    y=regret,
                    name='CF-CV',
                    mode='markers+lines',
                    marker=dict(size=25),
                    line=dict(color=colors[0], width=7))
        ]

        scatter_list.append(
            Scatter(x=np.r_[self.alpha_list[::-1], self.alpha_list],
                    y=np.r_[upper[::-1], lower],
                    showlegend=False,
                    fill='tozerox',
                    fillcolor=fill_colors[0],
                    mode='lines',
                    line=dict(color='rgba(255,255,255,0)')))

        scatter_list.append(
            Scatter(x=self.alpha_list,
                    y=np.mean(self.regret[:, 2], 0) *
                    np.ones_like(self.alpha_list),
                    name='Plug-in',
                    mode='markers+lines',
                    marker=dict(size=25),
                    line=dict(color=colors[1], width=7)))

        plot(Figure(data=scatter_list, layout=layout_regret_alpha),
             auto_open=False,
             filename=f'../plots/{self.data}/regret_alpha.html')
コード例 #12
0
def givenTaskHandler(id):
    ui = UsersInterface()
    user_id = session['user_id']
    ui.add_task_executor(task_id=int(id), user_id=user_id)
    tasks = ui.get_tasks()
    current_task = None
    for task in tasks:
        if task['id'] == int(id):
            current_task = task
    result = ui.fetch_task_results(current_task['id'])
    my_plot_div = plot([Scatter(x=result, y=[i for i in range(len(result))])],
                       output_type='div')
    # my_plot_div = plot([Scatter(y=[random.random() * 100 for i in range(1000)], x=[i for i in range(1000)])],
    #                    output_type='div')
    return render_template('givenTask.html',
                           div_placeholder=Markup(my_plot_div))
コード例 #13
0
ファイル: menu.py プロジェクト: darkreactions/ESCALATE
 def get(self, request, *args, **kwargs):
     x_data = [0, 1, 2, 3]
     y_data = [x**2 for x in x_data]
     plot_div = plot([
         Scatter(x=x_data,
                 y=y_data,
                 mode='lines',
                 name='test',
                 opacity=0.8,
                 marker_color='green')
     ],
                     output_type='div',
                     include_plotlyjs=False)
     vw_person = Person.objects.get(pk=request.user.person.pk)
     context = {'plot_div': plot_div, 'user_person': vw_person}
     return render(request, self.template_name, context=context)
コード例 #14
0
ファイル: views.py プロジェクト: Ajadelson/comphydro
def plot_web(xys, title, variable, unit, names=[]):
    data = [Scatter(x=xy[0], y=xy[1]) for xy in xys]
    if names:
        for i in range(len(data)):
            data[i].name = names[i]
    return plot(
        {
            'data':
            data,
            'layout':
            Layout(title=title,
                   xaxis={'title': _('time')},
                   yaxis={'title': "%s (%s)" % (str(variable), str(unit))})
        },
        auto_open=False,
        output_type='div')
コード例 #15
0
ファイル: lib.py プロジェクト: GuangYang14/friskby
def get_trace(sensor , start = None):    
    pair = sensor.get_vectors( start = start )
    if pair:
        ts , values = pair
        df = pd.DataFrame().from_dict({"ts" : ts , "values" : values})
        df.index = df['ts']

        #df.index = df.index + datetime.timedelta( hours=2 )
        df = df.resample('10Min')
        
        label = "%s : %s" % (sensor.parent_device.id , sensor.sensor_type)
        return Scatter( x=df.index,
                        y=df['values'],
                        name=label)
    else:
        return None
コード例 #16
0
def make_2d_scatter_trace(x, y, z, text_values, name=''):
    trace = Scatter(
        x=x,
        y=y,
        mode='markers',
        name=name,
        hoverinfo='text',
        text=text_values,
        marker={
            'size': 6,
            'color': 'red',
            'symbol': 'cross'
        },
        showlegend=False,
    )
    return trace
コード例 #17
0
ファイル: views.py プロジェクト: m-atisa/Icy-Analytics
    def get_context_data(self, **kwargs):
        context = {}
        x_data = [0, 1, 2, 3]
        y_data = [x**2 for x in x_data]
        plot_div = plot([
            Scatter(x=x_data,
                    y=y_data,
                    mode='lines',
                    name='test',
                    opacity=0.8,
                    marker_color='green')
        ],
                        output_type='div')
        context['graph'] = plot_div

        return render(self.request, template_name, context)
コード例 #18
0
def timeseries_analysis(values, filename):
    data = segment_by_type(values)
    texts = ["type_one", "type_two"]
    names = ["type_one", "type_two"]

    for_scatter = []
    for ind, val in enumerate(texts):
        x_vals, y_vals = prepare_for_timeseries(data[ind])
        for_scatter.append(
            Scatter(x=x_vals, y=y_vals, name=names[ind], text=val))

    plotly.offline.plot({
        "data": for_scatter,
        "layout": Layout(title="Time Series analysis")
    })
    shutil.move("temp-plot.html", filename)
 def make_trace(X, continent, sizes, color):
     return Scatter(
             x=X['GNP'],  # GDP on the x-xaxis
             y=X['LifeExpectancy'],  # life Exp on th y-axis
             name=continent,  # label continent names on hover
             mode='markers',  # (!) point markers only on this plot
             text=X.apply(make_text, axis=1).tolist(),
             marker=Marker(
                     color=color,  # marker color
                     size=sizes,  # (!) marker sizes (sizes is a list)
                     sizeref=sizeref,  # link sizeref
                     sizemode=sizemode,  # link sizemode
                     opacity=0.6,  # (!) partly transparent markers
                     line=Line(width=3, color="white")  # marker borders
             )
     )
コード例 #20
0
def percent_change_plot(*subreddits, days=1, plot_auto=True):
    data = []
    for title in subreddits:
        byte_code = get_page_source(title)
        subscribers, dates = number_of_subscribers(byte_code)
        percent_change = []
        for i in range(0, len(subscribers) - days):
            percent = 100 * (
                (subscribers[i + days] - subscribers[i]) / subscribers[i])
            percent_change.append(percent)
        trace = Scatter(x=dates, y=percent_change, mode='lines', name=title)
        data.append(trace)
    if plot_auto is True:
        plot(data)
    else:
        return data
コード例 #21
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
コード例 #22
0
def index():

    device = {
        'device_type': 'cisco_ios',
        'ip': '172.16.31.1',
        'username': '******',
        'password': '******',
    }

    flag = 1
    iter_out = ''

    used_mem_list = []
    time_list = []

    while 1:

        net_connect = ConnectHandler(**device)
        mem_out = net_connect.send_command('show process memory sorted')
        net_connect.disconnect()
        line_count = 0

        iter_out += '<br/>' + '<font face="verdana" color="green" size="4"><html><body><h1>' + 'Memory output iteration ' + str(
            flag) + '</h1></body></html></font>' + '<br/>'

        for line in mem_out.splitlines():
            iter_out += '<font face="Courier" size="2"><html><body><h1>' + line + '<br/>' + '</h1></body></html></font>'
            if line_count == 0:
                temp = line.split()
                used_mem_list.append(temp[5])
            line_count += 1
            if line_count == 10:
                break

        time_list.append(flag)
        if flag == 5:
            break
        sleep(1)
        flag = flag + 1

    my_plot_div = plot([Scatter(x=time_list, y=used_mem_list)],
                       output_type='div')
    plot_out = '<body>' + my_plot_div + '</body>'

    Output = plot_out + iter_out

    return Output
コード例 #23
0
def plot_marginal(spn, featureId, dictionary=None, fname=None, detail=100):
    marg = spn.marginalize([featureId])
    size = spn.numFeatures

    is_categorical = spn.featureTypes[featureId] == 'categorical'

    if is_categorical:
        enc = dictionary['features'][featureId]['encoder'].inverse_transform
        x_range = spn.domains[featureId]
        y_range = np.array([
            np.exp(func_from_spn(spn, featureId)(x)) for x in x_range
        ]).reshape(len(x_range))
        data = [Bar(
            x=enc(x_range),
            y=y_range,
        )]
    else:
        _min = spn.domains[featureId][0]
        _max = spn.domains[featureId][-1]
        if marg.leaf:
            turning_points = marg.x_range
        else:
            turning_points = np.concatenate([n.x_range for n in marg.children])
        turning_points = np.unique(
            np.sort(
                np.array([
                    p for p in turning_points if (p >= _min) and (p <= _max)
                ])))
        query = np.zeros((len(turning_points), spn.numFeatures))
        query[:, :] = np.nan
        query[:, featureId] = turning_points
        values = np.exp(marg.eval(query))
        data = [Scatter(
            x=turning_points,
            y=values,
            mode='lines',
        )]
    layout = dict(width=450,
                  height=450,
                  xaxis=dict(title=spn.featureNames[featureId]),
                  yaxis=dict(title='Probability density'
                             if not is_categorical else 'Probability'))

    if fname is None:
        return {'data': data, 'layout': layout}
    else:
        raise NotImplementedError
コード例 #24
0
ファイル: plot_centroids.py プロジェクト: sefcom/dbling
    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)
コード例 #25
0
def plot_clusters():

    X_tsne = np.load('data/X_tsne.npy')
    y_pred = np.load('data/y_pred_clusters.npy')
    text_labels = np.load('data/text_labels.npy', allow_pickle=True)

    disc_colors = px.colors.qualitative.Light24

    # define y-axis properties
    y_axis = dict(gridcolor='rgb(225, 225, 225)',
                  gridwidth=0.25,
                  linecolor='rgb(100, 100, 100)',
                  linewidth=2,
                  showticklabels=True,
                  color='black')
    # update x-axis params
    x_axis = y_axis.copy()
    x_axis.update(
        dict(ticks='outside',
             tickfont=dict(
                 family='Arial',
                 color='rgb(82, 82, 82)',
             )))
    # Scatter figure
    fig = Figure([
        Scatter(
            x=X_tsne[:, 0],
            y=X_tsne[:, 1],
            mode='markers',
            marker_color=y_pred,
            marker=dict(size=6, opacity=0.6, colorscale=disc_colors),
            text=text_labels,
        )
    ])
    # Edit layout
    fig.update_layout(
        title='Target Category Clusters (w/t-SNE & k-Means)',
        height=750,
        plot_bgcolor='white',
        yaxis=y_axis,
        xaxis=x_axis,
        #     showlegend=True,
        xaxis_title='Component 1',
        yaxis_title='Component 2',
    )

    return fig
コード例 #26
0
ファイル: teste.py プロジェクト: simonedjb/visualization-la
              def graph_03(self):

                  legend = {"title":"adicionar titulo",
                              "xaxis":"",
                              "yaxis":"",
                          }
                  if (self._language == "en"):
                      legend = {"title":"adicionar titulo", #bacalhau
                                  "xaxis":"",
                                  "yaxis":"",
                              }

                  color = ["rgb(127,0,0)","rgb(255,0,0)","rgb(127,0,127)","rgb(0,0,255)","rgb(0,127,127)","rgb(0,255,0)"]

                  dft = self.PROCDATASET
                  df = dft.set_index("Time")

                  sizeref = 0.01

                  trace = []
                  for i in range(0, len(df.columns[1:])):
                      trace.append(
                          Scatter(
                              x=df.index.get_level_values(0).values, #time
                              y=df.iloc[:,i].tolist(), #actions
                              hoverinfo='x+y',
                              mode='lines',

                              #stackgroup='one'

                          )
                      )


                  layout = Layout(

                  )

                  data = trace
                  fig=Figure(data=data, layout=layout)
                  if self._type_result == "jupyter-notebook":
                      iplot(fig, filename='Scatter')
                  elif self._type_result == "dash":
                      return dcc.Graph(
                          id='V009@3',
                          figure=fig
                      )
コード例 #27
0
ファイル: myapp.py プロジェクト: CetusGroup/dash-test
def gen_wind_speed(interval):
    now = dt.datetime.now()
    sec = now.second
    minute = now.minute
    hour = now.hour

    total_time = (hour * 3600) + (minute * 60) + (sec)

    con = sqlite3.connect("./Data/wind-data.db")
    df = pd.read_sql_query(
        'SELECT Speed, SpeedError, Direction from Wind where\
                            rowid > "{}" AND rowid <= "{}";'.format(
            total_time - 200, total_time), con)

    trace = Scatter(y=df['Speed'],
                    line=pscatter.Line(color='#42C4F7'),
                    hoverinfo='skip',
                    error_y=pscatter.ErrorY(type='data',
                                            array=df['SpeedError'],
                                            thickness=1.5,
                                            width=2,
                                            color='#B4E8FC'),
                    mode='lines')

    layout = Layout(height=450,
                    xaxis=dict(range=[200, 0],
                               showgrid=False,
                               showline=False,
                               zeroline=False,
                               fixedrange=True,
                               tickvals=[0, 50, 100, 150, 200],
                               ticktext=['200', '150', '100', '50', '0'],
                               title='Time Elapsed (sec)'),
                    yaxis=dict(range=[
                        min(0, min(df['Speed'])),
                        max(45,
                            max(df['Speed']) + max(df['SpeedError']))
                    ],
                               showline=False,
                               fixedrange=True,
                               zeroline=False,
                               nticks=max(6,
                                          round(df['Speed'].iloc[-1] / 10))),
                    margin=playout.Margin(t=45, l=50, r=45))

    return Figure(data=[trace], layout=layout)
コード例 #28
0
def daily_visualize(request):
    qs = Daily.objects.all()
    df = read_frame(qs)

    # import pdb;pdb.set_trace()

    plot_div = plot([
        Scatter(x=df.date,
                y=df.binn,
                mode='lines',
                name='test',
                opacity=0.8,
                marker_color='green')
    ],
                    output_type='div',
                    show_link=False)
    return render(request, "index.html", context={'plot_div': plot_div})
コード例 #29
0
def plot_sims(seed_id, word):
    import pandas as pd
    data = pd.read_csv(
        "/media/cluster/data1/lambert/lambert_w2v_data_jan_sims_" +
        str(seed_id) + ".csv",
        header=None,
        names=["id", "sims"])
    sims = data.sort("sims", axis=0, ascending=False).sims

    trace = Scatter(x=range(len(sims)), y=sims)

    data = [trace]
    layout = Layout(title="Similarities for word " + word,
                    xaxis=dict(title="n tweets"),
                    yaxis=dict(title="Cosine similarity"))
    fig = Figure(data=data, layout=layout)
    plot(fig)
コード例 #30
0
ファイル: views.py プロジェクト: IndiW/TeachTech
def teacher_view(request, *args, **kwargs):
    x_data = [2.4, 3.6, 7.2, 13.2, 25, 28.3, 35.3, 36.7, 37.5, 44.6]
    y_data = [0, -1, -1, 0, 1, 1, 1, 0, 0, -1]
    layout = Layout(title='Student Comprehension',
                    xaxis=dict(title='Timestamp',
                               titlefont=dict(family='Courier New, monospace',
                                              size=18,
                                              color='#7f7f7f')),
                    yaxis=dict(title='Comprehension',
                               titlefont=dict(family='Courier New, monospace',
                                              size=18,
                                              color='#7f7f7f')))
    data = Data([
        Scatter(x=x_data,
                y=y_data,
                mode='lines+markers',
                name='Comprehension Data',
                opacity=0.8,
                marker_color='blue')
    ])
    fig = Figure(data=data, layout=layout)
    plot_div = plot(fig, output_type='div')

    x_bar_data = ["3:34", "15:55", "24:48", "44:30"]
    y_bar_data = [2, 4, 3, 6]
    layout2 = Layout(title='Topics that needed repeating',
                     xaxis=dict(title='Timestamp',
                                titlefont=dict(family='Courier New, monospace',
                                               size=18,
                                               color='#7f7f7f')),
                     yaxis=dict(title='Number of votes',
                                titlefont=dict(family='Courier New, monospace',
                                               size=18,
                                               color='#7f7f7f')))
    data2 = Data([
        Bar(x=["3:34", "15:55", "24:48", "44:30"],
            y=[2, 4, 3, 6],
            name="Repeat Requests")
    ])
    fig2 = Figure(data=data2, layout=layout2)
    plot_div2 = plot(fig2, output_type='div')

    return render(request, "teacher.html", {
        'plot_div': plot_div,
        'plot_div2': plot_div2
    })