Beispiel #1
0
    def build_message_length_box(self):
        """
        Creates a bar plot of the total number of messages in each category
        :return: Object defining the plot, in Plotly format
        """
        boxes = []

        for genre in self.df["genre"].unique():
            category_message_lengths = self.df[
                self.df['genre'] == genre]['message'].apply(len).values
            boxes.append(Box(x=category_message_lengths, name=genre))

        return {
            'data': boxes,
            'layout': {
                'title': 'Distribution of Message Lengths per Genre',
                'xaxis': {
                    'title': "Message Length"
                }
            }
        }
Beispiel #2
0
def tab4_chart2(clicked_bandit, window, pradio, data):
    print('tab4 chart2')
    if data:
        proxies = data['proxies']

        if pradio == 'all':
            proxy_data = [{
                'y': proxy['response_times']
            } for proxy in proxies if proxy['bandit'][-1] == clicked_bandit
                          and len(proxy['response_times']) > 0]
        elif pradio == 'window':
            window = int(window)
            proxy_data = [{
                'y': proxy['response_times'][-window:]
            } for proxy in proxies if proxy['bandit'][-1] == clicked_bandit
                          and len(proxy['response_times']) > 0]

        data = [
            Box(y=proxy['y'], name='p' + str(i))
            for i, proxy in enumerate(proxy_data)
        ]
        data0 = Scatter(x=['p' + str(i) for i in range(0, len(proxy_data))],
                        y=[len(i['y']) for i in proxy_data],
                        yaxis='y2',
                        line=dict(width=1),
                        opacity=0.5)
        data.append(data0)

        layout = dict(showlegend=False,
                      title='Proxies response times in bandit ' +
                      str(clicked_bandit),
                      xaxis=dict(title='Proxy'),
                      yaxis=dict(title='Proxies reposne times [s]'),
                      yaxis2=dict(overlaying='y',
                                  side='right',
                                  title='Nr. of times used'),
                      margin=dict(l=50, r=80, t=80, b=50))

        return Figure(data=data, layout=layout)
Beispiel #3
0
def boxplot_min_energy_errors( schedule_names, experiment_outputs, title='', fsave='', x_axis='' ):
    n_exps = len( experiment_outputs[0].final_errors() )
    n_schedules = len( schedule_names )
    data = []
    for i in range(n_schedules):
        schedule_name = schedule_names[i]
        errors = experiment_outputs[i].min_energy_errors()
        data.append( Box(y=errors, boxpoints=False, name=schedule_name))
        
    
    
    layout = go.Layout( autosize=False, width=900, height=600,
                       margin=go.layout.Margin( l=60, r=75, b=100, t=100, pad=4 ),
                       title=title, showlegend=True, 
                       font = dict( color = "black",
                                   size = 10),
                       yaxis=dict(title='Error'),
                       xaxis=dict(title=x_axis))
    
    fig = Figure(data, layout)
    iplot(fig, filename=fsave)
    if len(fsave) > 0:
        pio.write_image(fig, fsave + '.pdf')
Beispiel #4
0
def get_mch_box(species, gene, level, outliers):
    """Generate gene body mCH box plot.

    Traces are grouped by cluster.

    Arguments:
        species (str): Name of species.
        gene (str):  Ensembl ID of gene for that species.
        level (str): Type of mCH data. Should be "original" or "normalized".
        outliers (bool): Whether if outliers should be displayed.

    Returns:
        str: HTML generated by Plot.ly.
    """
    points = get_gene_mch(species, gene, outliers)
    if not points:
        raise FailToGraphException

    traces = OrderedDict()
    max_cluster = int(
        max(points,
            key=lambda x: int(x['cluster_ordered']))['cluster_ordered']) + 1
    if species == 'mmu':
        max_cluster = 16
    colors = generate_cluster_colors(max_cluster)
    for point in points:
        trace = traces.setdefault(
            int(point['cluster_ordered']),
            Box(
                y=list(),
                name=point['cluster_name'],
                marker={
                    'color':
                    colors[(int(point['cluster_ordered']) - 1) % len(colors)],
                    'outliercolor':
                    colors[(int(point['cluster_ordered']) - 1) % len(colors)],
                    'size':
                    6
                },
                boxpoints='suspectedoutliers',
                visible=True,
            ))
        if level == 'normalized':
            trace['y'].append(point['normalized'])
        else:
            trace['y'].append(point['original'])

    if species == 'mmu':
        for i in range(17, 23, 1):
            traces[i]['marker']['color'] = 'black'
            traces[i]['marker']['outliercolor'] = 'black'
            traces[i]['visible'] = "legendonly"

    geneName = gene_id_to_name(species, gene)
    geneName = geneName['geneName']

    layout = Layout(
        autosize=False,
        width=950,
        height=700,
        title='Gene body mCH in each cluster: ' + geneName,
        titlefont={
            'color': 'rgba(1,2,2,1)',
            'size': 20
        },
        legend={
            'orientation': 'h',
            'y': -0.3,
            'traceorder': 'normal',
        },
        xaxis={
            'title': 'Cluster',
            'titlefont': {
                'size': 17
            },
            'type': 'category',
            'anchor': 'y',
            'ticks': 'outside',
            'ticklen': 4,
            'tickangle': -45,
            'tickwidth': 0.5,
            'showticklabels': True,
            'tickfont': {
                'size': 12
            },
            'showline': True,
            'zeroline': False,
            'showgrid': True,
            'linewidth': 1,
            'mirror': True,
        },
        yaxis={
            'title': geneName + ' ' + level.capitalize() + ' mCH',
            'titlefont': {
                'size': 15
            },
            'type': 'linear',
            'anchor': 'x',
            'ticks': 'outside',
            # 'tickcolor': 'white',
            'ticklen': 4,
            'tickwidth': 0.5,
            'showticklabels': True,
            'tickfont': {
                'size': 12
            },
            'showline': True,
            'zeroline': False,
            'showgrid': True,
            'linewidth': 1,
            'mirror': True,
        },
    )

    return plotly.offline.plot(
        {
            'data': list(traces.values()),
            'layout': layout
        },
        output_type='div',
        show_link=False,
        include_plotlyjs=False)
Beispiel #5
0
    def graph_03(self):
        legend = {
            "title":
            "Variação de notas dos estudantes por cluster de navegação",
            "xaxis": "",
            "yaxis": "Notas",
            'hovertext': 'Nota'
        }
        if (self._language == "en"):
            legend = {
                "title": "Student grades variation by navigate cluster",
                "xaxis": "",
                "yaxis": "Grades",
                'hovertext': 'Grade'
            }
        df = self.DATASET.sort_values(by=self.DATASET.columns[1])
        Clusters = df[df.columns[len(df.columns) - 1]].unique()
        color = ["rgb(198, 218, 32)", "rgb(121,64,64)", "rgb(0,0,204)"]
        color = ["rgb(255,0,0)", "rgb(0,0,255)", "rgb(0,255,0)"]
        # print(Clusters)
        trace = []
        for i in range(0, len(Clusters)):
            lst_grades = df[df.columns[1]].loc[df[df.columns[
                len(df.columns) - 1]] == Clusters[i]].values.tolist()  #Grades
            lst_names = df[df.columns[0]].loc[df[df.columns[
                len(df.columns) - 1]] == Clusters[i]].values.tolist()
            trace.append(
                Box(
                    y=lst_grades,
                    # y=df[df.columns[1]].loc[df[df.columns[len(df.columns)-1]]==Clusters[i]].values.tolist(), #Access
                    name="Cluster " + str(i + 1),
                    # text=df[df.columns[0]].loc[df[df.columns[len(df.columns)-1]]==Clusters[i]].values.tolist(),
                    text=[
                        '<b>' + lst_names[j] + '</b><br>' +
                        legend['hovertext'] + ": " + str(lst_grades[j]) +
                        '<br>Cluster ' + str(i + 1)
                        for j in range(len(lst_names))
                    ],
                    boxpoints='all',
                    marker=dict(color=color[i], line=dict(width=1)),
                    boxmean=True))

        layout = Layout(
            title=legend['title'],
            # hovermode = "closest",
            showlegend=True,
            xaxis=dict(
                title=legend["xaxis"],
                titlefont=dict(
                    # family='Arial, sans-serif',
                    # size=18,
                    color='rgb(180,180,180)', ),
            ),
            yaxis=dict(
                title=legend["yaxis"],
                titlefont=dict(
                    # family='Arial, sans-serif',
                    # size=18,
                    color='rgb(180,180,180)', ),
                fixedrange=False,
                range=[-1, self.DATASET[self.DATASET.columns[1]].max() + 10],
                rangemode="normal",
                # showline = True,
                zeroline=False,
            ))

        data = trace
        fig = Figure(data=data, layout=layout)
        if self._type_result == "jupyter-notebook":
            iplot(fig, filename='Box')
        elif self._type_result == "dash":
            return dcc.Graph(id='V011@3', figure=fig)
        elif self._type_result == "flask":
            modeBarButtonsToRemove = [
                'toImage', 'sendDataToCloud', 'hoverCompareCartesian',
                'lasso2d', 'hoverClosestCartesian', 'toggleHover',
                'hoverClosest3d', 'hoverClosestGeo', 'hoverClosestGl2d',
                'hoverClosestPie'
            ]
            config = {
                "displaylogo": False,
                "responsive": True,
                "displayModeBar": True,
                "modeBarButtonsToRemove": modeBarButtonsToRemove
            }
            return {
                "id":
                "V011@3",
                "layout":
                json.dumps({
                    "data": data,
                    "layout": layout,
                    "config": config
                },
                           cls=PlotlyJSONEncoder)
            }
Beispiel #6
0
def graph_mean_in_tissues(title, column_names, summary):
    """
    Compute plotly graph with mean value in tissue masks

    Parameters
    ----------
    title : string
        Title of the graph.
    column_names : array of strings
        Name of the columns in the summary DataFrame.
    summary : DataFrame
        DataFrame containing the mean stats.

    Returns
    -------
    div : html div (string)
        Graph as a HTML div.
    """
    means_wm = []
    means_gm = []
    means_csf = []
    np.random.seed(1)
    metric = np.concatenate(summary.index)
    means_wm = np.array(summary[column_names[0]])
    means_gm = np.array(summary[column_names[1]])
    means_csf = np.array(summary[column_names[2]])
    wm = Box(
        name="WM",
        y=means_wm,
        boxpoints='all',
        jitter=0.3,
        text=metric,
        pointpos=-1.8,
        hoverinfo="y+text"
    )

    gm = Box(
        name="GM",
        y=means_gm,
        boxpoints='all',
        jitter=0.3,
        text=metric,
        pointpos=-1.8,
        hoverinfo="y+text"
    )

    csf = Box(
        name="CSF",
        y=means_csf,
        boxpoints='all',
        jitter=0.3,
        text=metric,
        pointpos=-1.8,
        hoverinfo="y+text",
    )
    data = [wm, gm, csf]

    fig = Figure(data=data)

    range_yaxis = [0, np.max(means_wm) + 2 * np.max(means_wm)]

    fig['layout']['yaxis'].update(range=range_yaxis)
    fig['layout'].update(title=title)
    fig['layout'].update(width=500, height=500)
    div = off.plot(fig, show_link=False, output_type='div')
    div = div.replace("<div>", "<div style=\"display:inline-block\">")
    return div
Beispiel #7
0
            #mode = 'markers',
            name=op_type(key) + '-' + compression_type(key) + '-' + link_type(key),
            boxmean='sd',
            boxpoints='all'
        )
        )
'''

# Grouped Plot
for key, value in xxx.iteritems():
    if True:
        trace0.append(
            Box(
                x=value,
                y=yyy[key],
                #mode = 'markers',
                name=key,
                boxmean='sd',
                boxpoints='all'))

plotly.offline.plot({
    "data":
    sorted(trace0),
    "layout":
    Layout(title="Operations Per Second Sensitivity, Wired v. Wireless",
           yaxis=dict(title='operations per second'),
           boxmode='group')
})

# or plot with: plot_url = py.plot(data, filename='basic-line')
Beispiel #8
0
    def showPlotly(self):
        """

        :return:
        """
        title = " vs ".join(self.prefixes)
        imagefile = join(self.outputdir, "_".join(self.prefixes) + '.html')
        linewidth = 1.5
        markerdiam = 4
        errbarw = 3
        colors = {
            self.prefixes[0]: 'rgb(255,140,0)',
            self.prefixes[1]: 'rgb(70,130,180)'
        }
        # HistoAvg
        trace1 = []
        df = self.histodata
        for prefix in self.prefixes:
            meancol = 'MEAN_' + prefix
            semcol = 'SEM_' + prefix
            trace1.append(
                Scatter(x=df['bins'],
                        y=df[meancol],
                        name=prefix,
                        showlegend=False,
                        line=dict(width=linewidth, color=colors[prefix]),
                        marker=dict(color=colors[prefix], size=markerdiam),
                        error_y=dict(array=df[semcol],
                                     type='data',
                                     symmetric=True,
                                     color=colors[prefix],
                                     thickness=linewidth,
                                     width=errbarw)))

        # MSDAvg
        trace2 = []
        x = [str(x) for x in range(1, self.msdpoints + 1)]
        xi = [x * self.timeint
              for x in range(1, self.msdpoints + 1)]  # convert to times

        i = 0
        for file in self.msddatafiles:
            df = pd.read_csv(file)
            all = df.groupby('Cell').get_group('ALL')
            allmeans = all.groupby('Stats').get_group('Mean')
            allsems = all.groupby('Stats').get_group('SEM')
            trace2.append(
                Scatter(y=allmeans[x].iloc[0],
                        x=xi,
                        name=self.prefixes[i],
                        mode='lines+markers',
                        showlegend=False,
                        line=dict(color=colors[self.prefixes[i]],
                                  width=linewidth),
                        marker=dict(color=colors[self.prefixes[i]],
                                    size=markerdiam),
                        error_y=dict(array=allsems[x].iloc[0],
                                     type='data',
                                     symmetric=True,
                                     color=colors[self.prefixes[i]],
                                     thickness=linewidth,
                                     width=errbarw)))
            i += 1

        # Ratios
        trace3 = []
        df = self.ratiodata
        for prefix in self.prefixes:
            cols = 'Ratio_' + prefix
            trace3.append(
                Box(y=df[cols],
                    boxpoints='all',
                    showlegend=False,
                    jitter=0.3,
                    pointpos=-1.8,
                    name=prefix,
                    marker=dict(color=colors[prefix])))

        # Areas
        trace4 = []
        df = self.areadata[self.areadata['Cell'] != 'ALL']
        for prefix in self.prefixes:
            cols = 'MSD Area_' + prefix
            trace4.append(
                Box(y=df[cols],
                    boxpoints='all',
                    jitter=0.3,
                    pointpos=-1.8,
                    name=prefix,
                    marker=dict(color=colors[prefix])))

        fig = tools.make_subplots(
            rows=2,
            cols=2,
            subplot_titles=('Mean D with SEM', 'Mean MSD with SEM',
                            'Log10(D) Ratios', 'MSD Areas'))

        fig.append_trace(trace1[0], 1, 1)
        fig.append_trace(trace1[1], 1, 1)
        fig.append_trace(trace2[0], 1, 2)
        fig.append_trace(trace2[1], 1, 2)
        fig.append_trace(trace3[0], 2, 1)
        fig.append_trace(trace3[1], 2, 1)
        fig.append_trace(trace4[0], 2, 2)
        fig.append_trace(trace4[1], 2, 2)

        fig['layout'].update(height=800, width=800, title=title)
        fig['layout']['xaxis1'].update(title='Log<sub>10</sub>(D)')
        fig['layout']['yaxis1'].update(title='Relative Frequency')
        fig['layout']['xaxis2'].update(title='Time (s)')
        fig['layout']['yaxis2'].update(title='MSD (&mu;m<sup>2</sup>)')
        # fig['layout']['xaxis3'].update(title='Group')
        fig['layout']['yaxis3'].update(title='Mobile/Immobile Ratio')
        # fig['layout']['xaxis4'].update(title='Group')
        fig['layout']['yaxis4'].update(
            title='Area under curve (&mu;m<sup>2</sup>)')
        # py.plot(fig, filename=imagefile)
        offline.plot(fig, filename=imagefile)
Beispiel #9
0
def plot(yaxis_values, positions, yaxis_title,
         xaxis_title, plot_title, box_name):
    """
    Plot nba data

    :ages: list of the ages of players
    :positions: list of the positions
    :yaxis_title: title of the yaxis
    :xaxis_title: title of the xaxis
    :plot_title: title of the plot
    :box_name: name of the box

    :return:  None, data sent to plotly via API
    """
    data = Data([
        Box(
            y=yaxis_values,
            x=positions,
            name=box_name,
            boxmean=True,
            boxpoints='all',
            jitter=0.5,
            whiskerwidth=0.5,
            fillcolor='rgb(106, 168, 79)',
            marker=Marker(
                color='rgba(7, 55, 99, 0.5)',
                size=4,
                symbol='circle',
                opacity=0.7
            ),
            line=Line(
                color='rgba(7, 55, 99, 0.5)',
                width=2
            ),
            opacity=1,
            showlegend=False
        )
    ])
    layout = Layout(
        title=plot_title,
        showlegend=False,
        autosize=True,
        width=792,
        height=469,
        xaxis=XAxis(
            title=xaxis_title,
            range=[-0.6799999999999999, 6.5],
            type='category',
            autorange=True,
            showexponent='all',
            side='bottom'
        ),
        yaxis=YAxis(
            title=yaxis_title,
            range=[17.944444444444443, 39.05555555555556],
            type='linear',
            autorange=True,
            showexponent='all'
        ),
        paper_bgcolor='rgb(255, 255, 255)',
        plot_bgcolor='rgb(217, 217, 217)',
        hovermode='closest',
        boxmode='overlay',
        boxgap=0.4,
        boxgroupgap=0.4
    )
    fig = Figure(data=data, layout=layout)
    py.plot(fig)
Beispiel #10
0
Created on Thu Jul 20 15:03:07 2017

@author: Sayali Sonawane
"""
# Import packages
import numpy as np
import plotly
from plotly.graph_objs import Layout, Box

# Create data
y0 = np.random.randn(50) - 1
y1 = np.random.randn(50) + 1

# Define trace
trace1 = Box(y=y0,
             showlegend=True,
             marker=dict(color='rgb(214, 12, 140)', ),
             name='Trace_y0')
trace2 = Box(y=y1,
             showlegend=True,
             marker=dict(color='rgb(0, 128, 128)', ),
             name='Trace_y1')

# Create chart
# Output will be stored as a html file.
# Whenever we will open output html file, one popup option will ask us about if want to save it in jpeg format.
# Font family can be used in a layout to define font type, font size and font color for title
plotly.offline.plot(
    {
        "data": [trace1, trace2],
        "layout":
        Layout(title="Colored Box Chart",
Beispiel #11
0
def index():

    # extract data needed for visuals
    # TODO: Below is an example - modify to extract data for your own visuals
    genre_counts = df.groupby('genre').count()['message']
    genre_names = list(genre_counts.index)

    labels_list, num_obs_labels = _get_num_obs_per_label(df)

    df['words_count'] = df['message'].apply(lambda x: len(word_tokenize(x)))
    words_count_list = \
        list(df.words_count)

    words_count_list_filtered = list(df[df['words_count'] < 61].words_count)

    # create visuals
    # TODO: Below is an example - modify to create your own visuals
    graphs = [{
        'data': [Bar(x=genre_names, y=genre_counts)],
        'layout': {
            'title': 'Distribution of Message Genres',
            'yaxis': {
                'title': "Count"
            },
            'xaxis': {
                'title': "Genre"
            }
        }
    }, {
        'data': [Bar(x=num_obs_labels, y=labels_list, orientation='h')],
        'layout': {
            'title': 'Number of observations per label',
            'xaxis': {
                'title': "Label"
            }
        }
    }, {
        'data': [Histogram(x=words_count_list)],
        'layout': {
            'title': 'Histogram number of words per message',
            'xaxis': {
                'title': "Number of words"
            }
        }
    }, {
        'data': [Box(x=words_count_list)],
        'layout': {
            'title': 'Box Plot number of words per message'
        }
    }, {
        'data': [
            Histogram(x=words_count_list_filtered,
                      xbins=dict(size=2),
                      autobinx=False)
        ],
        'layout': {
            'title': 'Histogram number of words per message filtering only'
            ' messages with less then 61 words',
            'xaxis': {
                'title': "Number of words"
            }
        }
    }]

    # encode plotly graphs in JSON
    ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)

    # render web page with plotly graphs
    return render_template('master.html', ids=ids, graphJSON=graphJSON)
Beispiel #12
0
def append_bars_and_lines(data1, data2, data3, measure_results, table_rows):
    is_compare = measure_results[0].is_compare()
    results = {}
    versions = []
    webengine_compare = {}
    webkit_compare = {}
    webkit_labels = []
    for result in sorted(measure_results):
        if not is_compare:
            one_table_row = []
            if result.is_webengine():
                if result.get_engine() not in results:
                    results[result.get_engine()] = {}
                versions.append(result.get_version())
                results[result.get_engine()][
                    result.get_version()] = result.get_result()
                full_name = result.get_engine() + "-" + result.get_version()
                one_table_row.append(result.get_version())
            else:
                if re.match(".*QtWebkit-Annulen.*", result.get_engine()):
                    one_table_row.append("WK-A")
                else:
                    one_table_row.append("WK")
                if result.get_engine() not in results:
                    results[result.get_engine()] = []
                for i in range(0, 5):
                    results[result.get_engine()].append(result.get_result())
                full_name = result.get_engine()
            memories = result.get_memories()
            for memory in memories:
                one_table_row.append(memory)
            table_rows.append(one_table_row)
            data3.append(
                Box(y=memories, name=full_name, xaxis='x2', yaxis='y2'))
        else:
            if result.is_webengine():
                if result.get_gpu() not in webengine_compare:
                    webengine_compare[result.get_gpu()] = {}
                if not result.get_version() in versions:
                    versions.append(result.get_version())
                webengine_compare[result.get_gpu()][
                    result.get_version()] = result.get_result()
            else:
                if result.get_gpu() not in webkit_compare:
                    webkit_compare[result.get_gpu()] = {}
                webkit_compare[result.get_gpu()][
                    result.get_engine()] = result.get_result()
    versions = sorted(versions)
    if not is_compare:
        for key, values in sorted(results.items()):
            values_to_append = []
            if key == "QtWebEngine":
                for inner_key, inner_value in sorted(values.items()):
                    values_to_append.append(inner_value)
            else:
                values_to_append = values
            data2.append(
                Scatter(x=versions,
                        y=values_to_append,
                        mode='lines+markers+text',
                        name=key,
                        text=values_to_append,
                        textposition='top'))
            data1.append(
                Bar(x=versions,
                    y=values_to_append,
                    name=key,
                    text=values_to_append,
                    textposition='auto'))
    else:
        for key, values in webengine_compare.items():
            values_to_append = []
            for inner_key, inner_value in sorted(values.items()):
                values_to_append.append(inner_value)
            data1.append(
                Bar(x=versions,
                    y=values_to_append,
                    name=key,
                    text=values_to_append,
                    textposition='auto'))
        for key, values in sorted(webkit_compare.items()):
            values_to_append = []
            for inner_key, inner_value in sorted(values.items()):
                webkit_labels.append(inner_key)
                values_to_append.append(inner_value)
            data2.append(
                Bar(x=webkit_labels,
                    y=values_to_append,
                    name=key,
                    text=values_to_append,
                    textposition='auto'))
def index():
    
    # extract data needed for visuals
    # TODO: Below is an example - modify to extract data for your own visuals
    genre_counts = df.groupby('genre').count()['message']
    genre_names = list(genre_counts.index)
    
    classes_count = df.drop(columns = ['id','message','genre']).sum()
    classes_names = list(classes_count.index)
    
    text_length = df['message'].str.len()
    
    # create visuals
    # TODO: Below is an example - modify to create your own visuals
    graphs = [
        {
            'data': [
                Bar(
                    x=genre_names,
                    y=genre_counts
                )
            ],

            'layout': {
                'title': 'Distribution of Message Genres',
                'yaxis': {
                    'title': "Count"
                },
                'xaxis': {
                    'title': "Genre"
                },
                
            }
        },
        {
            'data': [
                Bar(
                    x=classes_names,
                    y=classes_count
                )
            ],

            'layout': {
                'title': 'Distribution of Classes in Training Data',
                'yaxis': {
                    'title': "Count"
                },
                'xaxis': {
                    'title': "Classes"
                }
            }
        },
        {
            'data': [
                Box(
                x = text_length,
                name = '' 
                )
            ],

            'layout': {
                'title': 'Box Plot of Text Length',
                'xaxis': {
                    'title': "Text length"
                }
            }
        }
                
    ]
    
    # encode plotly graphs in JSON
    ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)
    
    # render web page with plotly graphs
    return render_template('master.html', ids=ids, graphJSON=graphJSON)
Beispiel #14
0
def get_mch_box_two_species(species, gene_mmu, gene_hsa, level, outliers):
    """Generate gene body mCH box plot for two species.

    Traces are grouped by cluster and ordered by mm_hs_homologous_cluster.txt.
    Mouse clusters red, human clusters black.

    Arguments:
        gene_mmu (str):  Ensembl ID of gene for that species for mouse.
        gene_hsa (str):  Ensembl ID of gene for that species for human.
        level (str): Type of mCH data. Should be "original" or "normalized".
        outliers (bool): Whether if outliers should be displayed.

    Returns:
        str: HTML generated by Plot.ly.
    """
    points_mmu = get_gene_mch('mouse_published', gene_mmu, outliers)
    points_hsa = get_gene_mch(species, gene_hsa, outliers)
    cluster_order = get_ortholog_cluster_order()
    if not points_mmu or not points_hsa or not cluster_order:
        raise FailToGraphException

    geneName = gene_id_to_name('mouse_published', gene_mmu)
    geneName = geneName['geneName']

    # EAM - This organizes the box plot into groups
    traces_mmu = Box(y=list(
        i.get(level) for i in points_mmu if i.get('cluster_ortholog')),
                     x=list(
                         i.get('cluster_ortholog') for i in points_mmu
                         if i.get('cluster_ortholog')),
                     marker={
                         'color': 'red',
                         'outliercolor': 'red'
                     },
                     boxpoints='suspectedoutliers',
                     hoverinfo='text')
    traces_hsa = Box(y=list(
        i.get(level) for i in points_hsa if i.get('cluster_ortholog')),
                     x=list(
                         i.get('cluster_ortholog') for i in points_hsa
                         if i.get('cluster_ortholog')),
                     marker={
                         'color': 'black',
                         'outliercolor': 'black'
                     },
                     boxpoints='suspectedoutliers')
    traces_combined = [traces_mmu, traces_hsa]

    layout = Layout(
        boxmode='group',
        autosize=False,
        showlegend=False,
        width=900,
        height=700,
        title='Gene body mCH in each cluster: ' + geneName,
        titlefont={
            'color': 'rgba(1,2,2,1)',
            'size': 20
        },
        # legend={
        #     'orientation': 'h',
        #     'x': -0.1,
        #     'y': -0.6,
        #     'traceorder': 'normal',
        # },
        xaxis={
            'title': '',
            'titlefont': {
                'size': 14
            },
            'type': 'category',
            'anchor': 'y',
            'ticks': 'outside',
            'tickcolor': 'rgba(51,51,51,1)',
            'ticklen': 4,
            'tickwidth': 0.5,
            'tickangle': -35,
            'showticklabels': True,
            'tickfont': {
                'size': 12
            },
            'showline': False,
            'zeroline': False,
            'showgrid': True,
        },
        yaxis={
            'title': geneName + ' ' + level.capitalize() + ' mCH',
            'titlefont': {
                'size': 15
            },
            'type': 'linear',
            'anchor': 'x',
            'ticks': 'outside',
            'tickcolor': 'rgba(51,51,51,1)',
            'ticklen': 4,
            'tickwidth': 0.5,
            'showticklabels': True,
            'tickfont': {
                'size': 12
            },
            'showline': False,
            'zeroline': False,
            'showgrid': True,
        },
        shapes=[
            {
                'type': 'rect',
                'fillcolor': 'transparent',
                'line': {
                    'color': 'rgba(115, 115, 115, 1)',
                    'width': 1,
                    'dash': False
                },
                'yref': 'paper',
                'xref': 'paper',
                'x0': 0,
                'x1': 1,
                'y0': 0,
                'y1': 1
            },
        ],
        annotations=[{
            'text': '<b>■</b> Mouse',
            'x': 0.4,
            'y': 1.02,
            'ax': 0,
            'ay': 0,
            'showarrow': False,
            'font': {
                'color': 'red',
                'size': 12
            },
            'xref': 'paper',
            'yref': 'paper',
            'xanchor': 'left',
            'yanchor': 'bottom',
            'textangle': 0,
        }, {
            'text': '<b>■</b> Human',
            'x': 0.5,
            'y': 1.02,
            'ax': 0,
            'ay': 0,
            'showarrow': False,
            'font': {
                'color': 'Black',
                'size': 12
            },
            'xref': 'paper',
            'yref': 'paper',
            'xanchor': 'left',
            'yanchor': 'bottom',
            'textangle': 0,
        }])

    return plotly.offline.plot({
        'data': traces_combined,
        'layout': layout
    },
                               output_type='div',
                               show_link=False,
                               include_plotlyjs=False)
Beispiel #15
0
def jobsanalysis():
    with orm.db_session:
        countriesset = set(orm.select((c.country) for c in Stat)[:])
        keywords = orm.select((c.keyword) for c in Stat)[:]
    countries = [(k, allcountries[k]) for k in countriesset]
    #form.country.choices = countries
    #form.keyword.choices = [(x, x) for x in keywords]
    if request.method == 'GET':
        dataseries = []
        popularity = []
        plotly.tools.set_credentials_file(username='******',
                                          api_key='mYs3EJORl98E0vxkWvGr')
        keyword = ''
        countrytext = ''
        c = 0
        country = request.values.get('c', '')
        if country in allcountries:
            countrytext = allcountries[country]
            with orm.db_session:
                localarr = orm.select(
                    (c.keyword) for c in JobEntity if c.country == country)[:]
                for key in localarr:
                    yr = orm.select(
                        (c.minusdsalary) for c in JobEntity
                        if c.country == country and c.period == 'annum'
                        and c.keyword == key)[:]
                    dataseries.append(
                        Box(y=yr,
                            boxpoints=False,
                            name='Start %s' % key,
                            marker=dict(color=colors0[c])))
                    yr = orm.select(
                        (c.maxusdsalary) for c in JobEntity
                        if c.country == country and c.period == 'annum'
                        and c.keyword == key)[:]
                    dataseries.append(
                        Box(y=yr,
                            boxpoints=False,
                            name='Top %s' % key,
                            marker=dict(color=colors1[c])))
                    title = 'Salaries in %s for known keywords.' % countrytext
                    vacancies, days = orm.select(
                        (c.total, c.days) for c in Stat if c.country == country
                        and c.period == 'annum' and c.keyword == key)[:][0]
                    popularity.append(int(int(vacancies) / int(days)))
                    c += 1
        else:
            keyword = request.values.get('k', '')
            with orm.db_session:
                localarr = orm.select(
                    (c.country) for c in JobEntity if c.keyword == keyword)[:]
                for cnt in localarr:
                    yr = orm.select(
                        (c.minusdsalary) for c in JobEntity
                        if c.keyword == keyword and c.period == 'annum'
                        and c.country == cnt)[:]
                    dataseries.append(
                        Box(y=yr,
                            boxpoints=False,
                            name='Start %s' % cnt,
                            marker=dict(color=colors0[c])))
                    yr = orm.select(
                        (c.maxusdsalary) for c in JobEntity
                        if c.keyword == keyword and c.period == 'annum'
                        and c.country == cnt)[:]
                    dataseries.append(
                        Box(y=yr,
                            boxpoints=False,
                            name='Top %s' % cnt,
                            marker=dict(color=colors1[c])))
                    title = 'Salaries for jobs with keyword "%s".' % keyword
                    vacancies, days = orm.select(
                        (c.total, c.days) for c in Stat if c.country == cnt
                        and c.period == 'annum' and c.keyword == keyword)[:][0]
                    popularity.append(int(int(vacancies) / int(days)))
                    c += 1
        graph = getplotly(dataseries, Layout(title=title))
        dataseries_pop = [Bar(x=localarr, y=popularity)]
        graphp = getplotly(dataseries_pop,
                           Layout(title='Relevance, vacancies per day'))
    return render_template('parsers/graph.jade',
                           countries=countries,
                           keywords=keywords,
                           country=countrytext,
                           keyword=keyword,
                           graph=graph,
                           graphp=graphp)
Beispiel #16
0
#     json_error_list = json.dump(error_data, error_list_file)

# open error list from disk
with open(error_list_path, "r") as error_list_file:
    json_error_list = json.loads(error_list_file.read())

px_error_list = json_error_list["px"]
py_error_list = json_error_list["py"]
pz_error_list = json_error_list["pz"]
roll_error_list = json_error_list["roll"]
pitch_error_list = json_error_list["pitch"]
yaw_error_list = json_error_list["yaw"]

# prepare the data for the box plot for plotly to plot
# box plot taken here https://plot.ly/python/box-plots/
px_errors = Box(x=1, y=px_error_list, name='px')
py_errors = Box(x=2, y=py_error_list, name='py')
pz_errors = Box(x=3, y=pz_error_list, name='pz')
roll_errors = Box(x=4, y=roll_error_list, name='roll')
pitch_errors = Box(x=5, y=pitch_error_list, name='pitch')
yaw_errors = Box(x=6, y=yaw_error_list, name='yaw')
# data = [px_errors, py_errors, pz_errors, roll_errors, pitch_errors, yaw_errors]
# plot({"data": data})

px_errors = Histogram(x=px_error_list, name='px')
py_errors = Histogram(x=py_error_list, name='py')
pz_errors = Histogram(x=pz_error_list, name='pz')
roll_errors = Histogram(x=roll_error_list, name='roll')
pitch_errors = Histogram(x=pitch_error_list, name='pitch')
yaw_errors = Histogram(x=yaw_error_list, name='yaw')
Beispiel #17
0
def index():

    # extract data needed for visuals
    # TODO: Below is an example - modify to extract data for your own visuals
    genre_counts = df.groupby('genre').count()['message']
    genre_names = list(genre_counts.index)

    cat_names = df.columns.tolist()
    for x in ['id', 'message', 'original', 'genre']:
        cat_names.remove(x)
    cat_counts = df[cat_names].sum()

    df['length'] = df['message'].str.len()
    name_len_val = []
    for col in cat_names:
        name_len_val.append(df[df[col] == 1]['length'].values)

    data3 = []
    for i, name in enumerate(cat_names):
        data3.append(Box(y=name_len_val[i], name=name, boxpoints='outliers'))

    # create visuals
    # TODO: Below is an example - modify to create your own visuals
    graphs = [
        ####################### PLOT 1 ##########################
        {
            'data': [Bar(x=genre_names, y=genre_counts)],
            'layout': {
                'title': 'Distribution of Message Genres',
                'yaxis': {
                    'title': "Count"
                },
                'xaxis': {
                    'title': "Genre"
                }
            }
        },
        ####################### PLOT 2 ##########################
        {
            'data': [Bar(x=cat_names, y=cat_counts)],
            'layout': {
                'title': 'Distribution of Tagged Categories',
                'yaxis': {
                    'title': "Count"
                },
                'xaxis': {
                    'title': "Cat"
                }
            }
        },
        ####################### PLOT 3 ##########################
        {
            'data': data3,
            'layout': {
                'title': "Box Plot Styling Outliers",
                'yaxis': {
                    'type': 'log',
                    'autorange': 'True'
                }
            }
        }
    ]

    # encode plotly graphs in JSON
    ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
    graph1JSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)

    # render web page with plotly graphs
    return render_template('master.html', ids=ids, graphJSON=graph1JSON)
Beispiel #18
0
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 20 15:03:07 2017

@author: Sayali Sonawane
"""
# Import packages
import numpy as np
import plotly
from plotly.graph_objs import Layout,Box

# Create data 
y0 = np.random.randn(50)-1
y1 = np.random.randn(50)+1

# Define trace
trace1 =Box(x=y0,showlegend=True,name='Trace_y0')
trace2 =Box(x=y1,showlegend=True,name='Trace_y1')

# Create chart 
# Output will be stored as a html file. 
# Whenever we will open output html file, one popup option will ask us about if want to save it in jpeg format.
# Font family can be used in a layout to define font type, font size and font color for title           
plotly.offline.plot({
                         "data": [
                                  trace1,trace2
                                  ], 
                        "layout": Layout(title="Basic Horizontal Box Chart",font=dict(family='Courier New, monospace', size=18, color='rgb(0,0,0)'))
                                  },filename='basic_horizontal_box_chart.html',image='jpeg')
Beispiel #19
0
def plotBoxplot(db, table, **xargs):
    data = read(db, table)
    return _plotly(
        [Box(x=v.get("x", None), y=v["y"], name=k) for k, v in data.items()],
        table, **xargs)