Пример #1
0
def updateFigEducEnvir(envir, disType):
    df = dfs_sum([educaEnvir[dis].df for dis in disType])
    if len(envir) == 1:
        trace = go.Pie(labels=df.index.values, values=df[envir[0]].tolist())
        return {
            'data': [trace],
            'layout': {
                'title':
                "Niveau d'éducation dans le monde " + envir[0].lower(),
            }
        }
    else:
        trace = go.Sunburst(
            ids=[env for env in envir] + [
                env + " - " + level for env in envir
                for level in df.index.values
            ],
            labels=[env
                    for env in envir] + [level
                                         for level in df.index.values] * 4,
            parents=["" for i in range(len(envir))] +
            list(chain.from_iterable((env, env, env, env) for env in envir)),
            values=[df[env].sum() for env in envir] +
            [df.loc[level][env] for env in envir for level in df.index.values],
            branchvalues="total",
        )
        return {
            'data': [trace],
            'layout': {
                'title': "Niveau d'éducation par environment",
            }
        }
Пример #2
0
def treemap(value):

    #values = [500, 433, 78, 25, 25, 7]
    values = rfm['Segment'].value_counts().values
    index = rfm['Segment'].value_counts().index
    parents_segment = rfm['Segment'].head(20).values
    childs = rfm['CustomerID'].head(20).values
    segment_counts = rfm['Counts'].head(20).values

    # Choose colors from http://colorbrewer2.org/ under "Export"

    trace = go.Sunburst(ids=childs,
                        labels=parents_segment,
                        values=segment_counts,
                        outsidetextfont={
                            "size": 20,
                            "color": "#377eb8"
                        },
                        marker={"line": {
                            "width": 2
                        }},
                        maxdepth=2)

    layout = go.Layout(margin=go.layout.Margin(t=0, l=0, r=0, b=0))

    #  fig = {'data':  trace, 'layout':layout}
    fig = go.Figure([trace], layout)
    return fig
Пример #3
0
def create_figure_sunburst(df_sunburst, kiez):
    # create dataframe for age brackets
    df_brackets = df_sunburst.groupby('bracket', as_index=False).sum()

    df_sunburst.replace({'below_6': '<6', '65_above': '65+'}, inplace=True)

    labels = [kiez] + df_brackets.bracket.tolist() + df_sunburst.age.tolist()
    parents = [""] + [kiez] * len(df_brackets) + df_sunburst.bracket.tolist()
    counts = np.array([df_sunburst['count'].sum()] +
                      df_brackets['count'].tolist() +
                      df_sunburst['count'].tolist())

    fig_sunburst = go.Figure(
        go.Sunburst(
            labels=labels,
            parents=parents,
            values=counts,
            insidetextorientation='radial',
            marker=dict(
                colors=counts,
                colorscale='deep',
            ),
            # hovertemplate='Numer of trips to <b>%{label}</b>:<br> %{customdata[0]:,}<extra></extra>',
        ))

    fig_sunburst.update_layout(**fig_layout_defaults,
                               margin=dict(t=0, l=0, r=0, b=0))

    return fig_sunburst
Пример #4
0
    def build_graph_figure(self, figure_layout=go.Layout(), pos=None):
        """
        Building the graph plot figure.
        :param figure_layout: a plot.ly layout object.
        :param pos: place holder
        """

        structure = {node: "" for node in self.graph.nodes()}

        for edge in self.graph.edges():
            parent, label = edge
            structure[label] = parent

        hover_text = [
            node_data['label'] if 'label' in node_data else ''
            for node, node_data in self.graph.nodes(data=True)
        ]

        data = [
            go.Sunburst(labels=list(structure.keys()),
                        parents=list(structure.values()),
                        hovertext=hover_text,
                        hoverinfo="text",
                        textinfo='text',
                        text=['' for _ in range(len(structure.values()))])
        ]

        self.graph_figure = go.Figure(data=data, layout=figure_layout)
Пример #5
0
def get_sunburst_figure():

    cell_count_labels = cell_counts.get_cell_type_labels_counts()

    cell_types = \
        [cell_count_label[0] for cell_count_label in cell_count_labels]
    friendly_labels = \
        [cell_count_label[1] for cell_count_label in cell_count_labels]
    friendly_parent_labels = \
        [cell_count_label[2] for cell_count_label in cell_count_labels]
    cell_types_counts = \
        [cell_count_label[3] for cell_count_label in cell_count_labels]

    return {
        "data": [
            graph_objects.Sunburst(
                labels=friendly_labels,
                parents=friendly_parent_labels,
                values=cell_types_counts,
                branchvalues="total",
                leaf={"opacity": 1.0},
                marker=dict(colors=[
                    config.CELL_TYPE_HIERARCHICAL_COLORS[cell_type]
                    for cell_type in cell_types
                ]))
        ],
        "layout":
        graph_objects.Layout(title="Cell Type Distribution",
                             showlegend=False,
                             autosize=True)
    }
Пример #6
0
 def modifyCircles(self):
     processbook = self.ddlValues.currentText()
     if (processbook != 'Selecciona un dato'):
         if (self.circle >= 0):
             processes = self.exec(QUERYBIGDATA.format(processbook))
             parents = [""] + self.getColumn(processes, 0)
             names = [processbook] + self.getColumn(processes, 1)
             counts = self.getColumn(processes, 2)
             total = self.getTotal(counts)
             values = [total] + counts
             title = 'Grandes datos de {0}'.format(processbook)
             if (self.circle >= 1):
                 tables = self.exec(QUERYTOTALLIST.format(processbook))
                 parents = parents + self.getColumn(tables, 0)
                 newValues = self.getColumn(tables, 2)
                 if (self.circle == 1):
                     names = names + \
                         self.getPercentages(self.getColumn(
                             tables, 1), newValues, total)
                 else:
                     names = names + self.getColumn(tables, 1)
                 values = values + newValues
                 title = 'Lista total de {0}'.format(processbook)
             fig = go.Figure(
                 go.Sunburst(
                     labels=names,
                     parents=parents,
                     values=values,
                     branchvalues="total",
                 ))
             self.show(fig, title)
Пример #7
0
 def modifyCircles(self):
     bigdata = self.ddlBigData.currentText()
     if (bigdata != 'Selecciona un dato'):
         if (self.circle >= 0):
             processes = self.exec(QUERYPROCESSES.format(bigdata))
             parents = [""] + self.getColumn(processes, 0)
             names = [bigdata] + self.getColumn(processes, 1)
             counts = self.getColumn(processes, 2)
             total = self.getTotal(counts)
             values = [total] + counts
             title = 'Procesos de {0}'.format(bigdata)
             if (self.circle >= 1):
                 tables = self.exec(QUERYSUBPROCESSES.format(bigdata))
                 parents = parents + self.getColumn(tables, 0)
                 newValues = self.getColumn(tables, 2)
                 if (self.circle == 1):
                     names = names + \
                         self.getPercentages(self.getColumn(
                             tables, 1), newValues, total)
                 else:
                     names = names + self.getColumn(tables, 1)
                 values = values + newValues
                 title = 'Procesos y documentos de {0}'.format(bigdata)
             fig = go.Figure(
                 go.Sunburst(
                     labels=names,
                     parents=parents,
                     values=values,
                     branchvalues="total",
                 ))
             self.show(fig, title)
Пример #8
0
def updateFigEducEnvir(envir, disType):
    global layout, my_colors, my_line_colors
    my_colors1 = [
        'rgb(136, 207, 241)', 'rgb(249, 215, 214)', 'rgb(184, 235, 255)',
        'rgb(255, 184, 199)'
    ]
    layout1 = copy.deepcopy(layout)
    layout1['title'] = "Niveau d'éducation dans le monde " + envir[0].lower()
    df = dfs_sum([educaEnvir[dis].df for dis in disType])
    if len(envir) == 1:
        trace = go.Pie(labels=df.index.values,
                       values=df[envir[0]].tolist(),
                       marker_colors=my_colors1,
                       hole=.3,
                       opacity=0.7)
        return {'data': [trace], 'layout': layout1}
    else:
        layout1 = copy.deepcopy(layout)
        layout1['title'] = "Niveau d'éducation par environment"
        trace = go.Sunburst(
            ids=[env for env in envir] + [
                env + " - " + level for env in envir
                for level in df.index.values
            ],
            labels=[env
                    for env in envir] + [level
                                         for level in df.index.values] * 4,
            parents=["" for i in range(len(envir))] +
            list(chain.from_iterable((env, env, env, env) for env in envir)),
            values=[df[env].sum() for env in envir] +
            [df.loc[level][env] for env in envir for level in df.index.values],
            branchvalues="total",
            marker=dict(colors=my_colors, autocolorscale=True))
        return {'data': [trace], 'layout': layout1}
Пример #9
0
def create_figure_sunburst(df_outflow_top, df_outflow_rest, df_outflow_borough,
                           pickup_zone):
    for df in [df_outflow_borough, df_outflow_top]:
        df['dropoff_borough_name'] = df.dropoff_borough.astype('int').map(
            borough_index_to_name)
    for df in [df_outflow_top]:
        df['dropoff_zone_name'] = df.dropoff_zone.astype('int').map(
            zone_index_to_name)
        df['dropoff_borough_name'] = df.dropoff_borough.astype('int').map(
            borough_index_to_name)

    start_name = zone_index_to_name[pickup_zone]
    labels = [start_name] + df_outflow_borough.dropoff_borough_name.tolist(
    ) + df_outflow_top.dropoff_zone_name.tolist()
    parents = [""] + [start_name] * len(
        df_outflow_borough) + df_outflow_top.dropoff_borough_name.tolist()
    counts = np.array([len(df)] + df_outflow_borough.count_trips.tolist() +
                      df_outflow_top.count_trips.tolist())

    fig_sunburst = go.Figure(
        go.Sunburst(
            labels=labels,
            parents=parents,
            values=np.log10(counts + 10),
            customdata=np.stack([counts], axis=-1),
            hovertemplate=
            'Numer of trips to <b>%{label}</b>:<br> %{customdata[0]:,}<extra></extra>',
            # branchvalues="total"
        ))
    fig_sunburst.layout = go.Layout(**fig_layout_defaults)
    return fig_sunburst
Пример #10
0
def plot_ski_jumping_sunburst():
    pd.set_option('display.max_rows', 100)

    df = pd.read_csv('athlete_events.csv')
    df = df[df['Year'] >= 2000]
    df = df[df['Event'].str.contains("Ski Jumping Men's")]
    df = df[df['Medal'].notna()]

    grouped = df.groupby(['Team', 'Medal']).size()
    print(grouped)
    # print(grouped.index)

    # teams = grouped.index.levels[0]
    # medals = grouped.index.levels[1]
    # print(grouped.loc['Austria'])
    # print(grouped.loc['Austria', 'Gold'])
    ids = []
    labels = []
    parents = []
    values = []
    colors = []

    medals_colors = {
        'Bronze': '#9C5843',
        'Silver': '#C0C0C0',
        'Gold': '#FFD700'
    }

    for team in grouped.index.levels[0]:
        team_id = f'{team}_all'
        team_total_count = 0

        medal_types = grouped.loc[team]
        for medal in medal_types.index:
            count = medal_types.loc[medal]
            ids.append(f'{team}_{medal}')
            labels.append(medal)
            parents.append(team_id)
            values.append(count)
            team_total_count += count
            colors.append(medals_colors.get(medal))

        ids.append(team_id)
        labels.append(team)
        parents.append('')
        values.append(team_total_count)
        colors.append(None)

    trace = go.Sunburst(ids=ids,
                        labels=labels,
                        parents=parents,
                        values=values,
                        marker=dict(colors=colors),
                        branchvalues="total")

    layout = go.Layout()
    figure = go.Figure(data=[trace], layout=layout)
    plot(figure, auto_open=True, filename='ski_jumping.html')
Пример #11
0
def ontology_figures(ontology_data):
    ontology_sunburst_figure = go.Figure(go.Sunburst(labels=ontology_data['labels'], parents=ontology_data['parents'], maxdepth=2))
    ontology_treemap_figure = go.Figure(go.Treemap(labels=ontology_data['labels'], parents=ontology_data['parents']))

    ontology_sunburst_figure.update_layout(margin=spacing, height=height, polar_bgcolor=bg_color, paper_bgcolor=bg_color,
                                           font_size=font_size, font_color=font_color)
    ontology_treemap_figure.update_layout(margin=spacing, height=height, polar_bgcolor=bg_color, paper_bgcolor=bg_color,
                                          font_size=font_size, font_color=font_color)

    return [ontology_treemap_figure, ontology_sunburst_figure]
Пример #12
0
def update_graph7(input_data):
    algo = dictionary_dimension_conversion(Graph8_Data)
    dictionary_1 = algo.dict_conversion()
    total = algo.dict_total()

    labels2 = ["Total"]
    parents2 = [""]
    values2 = [total]

    sunburst_random = random.uniform(0.8, 1.2)

    for key, value in dictionary_1.items():
        labels2.append(key)
        parents2.append("Total")
        values2.append(value)

        label_extension = list(Graph8_Data.get(key).keys())

        product_line = key + " "
        product_line_list = ((product_line * len(label_extension)).split(" "))
        product_line_list.pop()
        parents_extension = product_line_list

        values_extension = list(Graph8_Data.get(key).values())

        labels2.extend(label_extension)
        parents2.extend(parents_extension)
        values2.extend(values_extension)

    #value3 = list(map(lambda x: x * sunburst_random, values2))
    #value_to_show = list(map(lambda x: int(x), value3))

    value_to_show = algo.introduce_variation(labels2, values2)

    data = go.Sunburst(labels=labels2,
                       parents=parents2,
                       values=value_to_show,
                       branchvalues="total",
                       maxdepth=2)

    layout = {
        "title": "Popular Sentiments of each Product Line",
        "margin": {
            "l": 20,
            "t": 100,
            "b": 20,
            "r": 20
        },
        "clickmode": "event+select"
    }

    return {"data": [data], "layout": layout}
Пример #13
0
def updateFigEmplStatus(states, years):
    if len(years) > 1:
        selectedExtendedDfsForYear1 = toolz.dfSelector(
            toolz.dfSelector(
                toolz.dfSelector(usaData.dfsArray, 'index',
                                 ['EMPLOYMENT SECTOR']), 'state', states),
            'year', [years[0]])
        dfYear1 = dfs_sum(
            [df['dataFrame'] for df in selectedExtendedDfsForYear1])
        selectedExtendedDfsForYear2 = toolz.dfSelector(
            toolz.dfSelector(
                toolz.dfSelector(usaData.dfsArray, 'index',
                                 ['EMPLOYMENT SECTOR']), 'state', states),
            'year', [years[1]])
        dfYear2 = dfs_sum(
            [df['dataFrame'] for df in selectedExtendedDfsForYear2])
        trace = go.Sunburst(
            ids=["20" + year for year in years] + [
                "20" + year + " - " + status for year in years
                for status in dfYear1.columns.tolist()
            ],
            labels=["20" + year for year in years] +
            [status for status in dfYear1.columns.tolist()] * 2,
            parents=["" for i in range(len(years))] + list(
                chain.from_iterable(
                    ("20" + year, "20" + year) for year in years)),
            values=[dfYear1.iloc[0, :].sum(), dfYear2.iloc[0, :].sum()] + [
                dfYear1.iloc[0, 0], dfYear1.iloc[0, 1], dfYear2.iloc[0, 0],
                dfYear2.iloc[0, 1]
            ],
            branchvalues="total",
        )
        return {
            'data': [trace],
            'layout': {
                'title': "EMPLOYMENT STATUS".title()
            }
        }
    else:
        selectedExtendedDfs = toolz.dfSelector(
            toolz.dfSelector(
                toolz.dfSelector(usaData.dfsArray, 'index',
                                 ['EMPLOYMENT SECTOR']), 'state', states),
            'year', [years[0]])
        df = dfs_sum([df['dataFrame'] for df in selectedExtendedDfs])
        trace = go.Pie(labels=df.columns.tolist(), values=df.iloc[0].tolist())
        return {
            'data': [trace],
            'layout': {
                'title': "EMPLOYMENT STATUS".title()
            }
        }
def get_suburst_plot(labels, parents, values, return_trace = False, filename = None):
    trace = go.Sunburst(labels = labels, parents = parents, values = values, branchvalues = "total", 
                        marker = dict(colorscale='Emrld'))
    if return_trace:
        return trace

    fig = go.Figure(trace)
    fig.update_layout(margin = dict(t = 0, b = 0, r = 0, l = 0))
    
    if filename is not None:
        fig.write_html(filename, include_plotlyjs = 'cdn')
    else:
        fig.show()
Пример #15
0
    def render_sunburst_plot(self):
        # Create the figure
        fig = go.Figure(
            go.Sunburst(ids=self.ids,
                        labels=self.labels,
                        parents=self.parents,
                        values=self.values,
                        branchvalues="total",
                        insidetextorientation='radial'))
        # Update layout for tight margin
        fig.update_layout(title=self.plot_title, margin=dict(l=0, r=0, b=0))

        fig.show()
Пример #16
0
def updateFigEmplStatus(states, years):
    global layout, my_colors, my_line_colors
    my_colors1 = copy.deepcopy(my_colors).extend(my_line_colors)
    layout1 = copy.deepcopy(layout)
    layout1['title'] = "EMPLOYMENT STATUS".title()
    if len(years) > 1:
        selectedExtendedDfsForYear1 = toolz.dfSelector(
            toolz.dfSelector(
                toolz.dfSelector(usaData.dfsArray, 'index',
                                 ['EMPLOYMENT SECTOR']), 'state', states),
            'year', [years[0]])
        dfYear1 = dfs_sum(
            [df['dataFrame'] for df in selectedExtendedDfsForYear1])
        selectedExtendedDfsForYear2 = toolz.dfSelector(
            toolz.dfSelector(
                toolz.dfSelector(usaData.dfsArray, 'index',
                                 ['EMPLOYMENT SECTOR']), 'state', states),
            'year', [years[1]])
        dfYear2 = dfs_sum(
            [df['dataFrame'] for df in selectedExtendedDfsForYear2])
        trace = go.Sunburst(
            ids=["20" + year for year in years] + [
                "20" + year + " - " + status for year in years
                for status in dfYear1.columns.tolist()
            ],
            labels=["20" + year for year in years] +
            [status for status in dfYear1.columns.tolist()] * 2,
            parents=["" for i in range(len(years))] + list(
                chain.from_iterable(
                    ("20" + year, "20" + year) for year in years)),
            values=[dfYear1.iloc[0, :].sum(), dfYear2.iloc[0, :].sum()] + [
                dfYear1.iloc[0, 0], dfYear1.iloc[0, 1], dfYear2.iloc[0, 0],
                dfYear2.iloc[0, 1]
            ],
            branchvalues="total",
            marker=dict(colors=my_colors, autocolorscale=True))
        return {'data': [trace], 'layout': layout1}
    else:
        selectedExtendedDfs = toolz.dfSelector(
            toolz.dfSelector(
                toolz.dfSelector(usaData.dfsArray, 'index',
                                 ['EMPLOYMENT SECTOR']), 'state', states),
            'year', [years[0]])
        df = dfs_sum([df['dataFrame'] for df in selectedExtendedDfs])
        trace = go.Pie(labels=df.columns.tolist(),
                       values=df.iloc[0].tolist(),
                       marker_colors=my_colors,
                       hole=.3,
                       opacity=0.7)
        return {'data': [trace], 'layout': layout1}
Пример #17
0
def update_mistake_starburst(*args, **kwargs):
    callback = kwargs['callback_context']
    user = kwargs['user']
    subject_pk = callback.inputs['subject-dropdown.value']
    students = get_students_from_graph(callback, user)

    # Keep blank if we haven't loaded all charts yet.
    if not students:
        return False
    root_pk = get_root_pk(callback)
    if not root_pk:
        return False
    parent_point = Syllabus.objects.get(pk=root_pk)

    mistakes = Mistake.objects.all()
    sittings = set_sittings(callback, user)
    labels = [mistake.mistake_type for mistake in mistakes]
    ids = [mistake.pk for mistake in mistakes]
    parents = []
    for mistake in mistakes:
        if mistake.parent:
            parents.append(mistake.parent.mistake_type)
        else:
            parents.append("")

    parents[0] = ""
    values = [1 for mistake in mistakes]
    colors = [mistake.cohort_totals(students, parent_point.get_descendants(), sittings) for mistake in mistakes]
    graph = go.Sunburst(
        labels=labels,
        parents=parents,
        values=values,
        customdata=ids,
        marker=dict(colors=colors,
                    colorscale='gnbu',
                    cmin=0),
        hovertemplate='<b>%{label}</b><br>Total Mistakes: %{color}',
        name='',

    )
    layout = go.Layout(
        margin=dict(t=0, l=0, r=0, b=0),
        uniformtext=dict(minsize=10, mode='hide'),
        title='Syllabus Performance Explorer',
        showlegend=False

    )

    return {'data': [graph], 'layout': layout}
Пример #18
0
 def showContract(self):
     labels = [str(self.total)]
     parents = [""]
     values = [self.total]
     for parent in self.dataParents:
         labels.append(parent[0])
         parents.append(str(self.total))
         values.append(parent[1])
     fig = go.Figure(
         go.Sunburst(
             labels=labels,
             parents=parents,
             values=values,
             branchvalues="total",
         ))
     self.show(fig, self.title)
Пример #19
0
def plot(filename):
    """Plot sunburst chart from data given in stdin."""
    sizes, paths = zip(*map(split_line, sys.stdin))
    paths_set = set(paths)
    parents, labels = zip(*map(lambda p: split_path(p, paths_set), paths))

    trace = go.Sunburst(ids=paths,
                        labels=labels,
                        parents=parents,
                        values=sizes,
                        branchvalues='total')
    fig = go.Figure([trace])

    if filename.endswith('html'):
        fig.write_html(filename)
    else:
        fig.write_image(filename)
Пример #20
0
def sun_plot():
    fig = go.Figure(
        go.Sunburst(
            labels=[
                'White', 'Yellow', 'Orange', 'Brown', 'Red', 'Magenta', 'Pink',
                'Lavender', 'Purple', 'Blue'
            ],
            parents=[
                'White', 'Yellow', 'Orange', 'Brown', 'Red', 'Magenta', 'Pink',
                'Lavender', 'Purple', 'Blue'
            ],
            values=[31, 27, 6, 1, 15, 9, 19, 6, 22, 7],
            branchvalues="total",
        ))

    fig.update_layout(title_text='Brust of Flowers by Colors')
    return fig.show()
Пример #21
0
def sundial_plot(metric='SP.POP.TOTL', title='World Population', year=2000):
    """Plot the given metric as a sundial plot"""
    countries = wb.get_countries()
    values = wb.get_series(metric,
                           date=year,
                           id_or_value='id',
                           simplify_index=True)

    df = countries[['region', 'name']].rename(columns={
        'name': 'country'
    }).loc[countries.region != 'Aggregates']
    df['values'] = values

    # The sunburst plot requires weights (values), labels, and parent (region, or World)
    # We build the corresponding table here
    columns = ['parents', 'labels', 'values']

    level1 = df.copy()
    level1.columns = columns
    level1['text'] = level1['values'].apply(lambda pop: '{:,.0f}'.format(pop))

    level2 = df.groupby('region')['values'].sum().reset_index()[[
        'region', 'region', 'values'
    ]]
    level2.columns = columns
    level2['parents'] = 'World'
    # move value to text for this level
    level2['text'] = level2['values'].apply(lambda pop: '{:,.0f}'.format(pop))
    level2['values'] = 0

    level3 = pd.DataFrame({
        'parents': [''],
        'labels': ['World'],
        'values': [0.0],
        'text': ['{:,.0f}'.format(values.loc['WLD'])]
    })

    all_levels = pd.concat([level1, level2, level3],
                           axis=0).reset_index(drop=True)

    return go.Figure(data=[go.Sunburst(hoverinfo='text', **all_levels)],
                     layout=go.Layout(title='{} (World Bank, {})'.format(
                         title, year),
                                      width=800,
                                      height=800))
Пример #22
0
def updateFigIllit(sexe, disType, envir):
    df = dfs_sum([illitSexeEnvir[dis].df for dis in disType]).loc[envir][sexe]
    if len(sexe) == 1:
        trace = go.Pie(labels=envir,
                       values=df.loc[envir[0]].tolist() +
                       df.loc[envir[1]].tolist())
    else:
        trace = go.Sunburst(
            ids=[env for env in envir] +
            [env + " - " + sex for env in envir for sex in sexe],
            labels=[env for env in envir] + [sex for sex in sexe] * 2,
            parents=["" for i in range(len(envir))] +
            list(chain.from_iterable((env, env) for env in envir)),
            values=[df.loc[env].sum() for env in envir] +
            [df.loc[env][sex] for env in envir for sex in sexe],
            branchvalues="total",
        )

    return {'data': [trace], 'layout': {}}
Пример #23
0
def plot_sunburst(df, sample_id):
    # example sample ID
    df_sample = df[['phylum', 'class',
                    'weight']][df['sample_id'] == int(sample_id)]

    # double group by
    df_sample = df_sample.groupby(['phylum', 'class']).sum()
    df_sample.reset_index(inplace=True)

    # define hierarchy for sunburst plot
    tax_labels = list(df_sample['class'])
    tax_parents = list(df_sample['phylum'])

    # values
    values = df_sample['weight'].tolist()

    # add kingdom to pylum relationship
    for phyla in list(df_sample['phylum'].unique()):
        tax_labels.append(phyla)
        tax_parents.append('Bacteria')
        values.append(1)

    # add kingdom as center of sunburst
    tax_labels.append('Bacteria')
    tax_parents.append("")

    # plot sunbust
    trace = go.Sunburst(labels=tax_labels,
                        parents=tax_parents,
                        values=values,
                        outsidetextfont={
                            "size": 20,
                            "color": "#377eb8"
                        },
                        marker={"line": {
                            "width": 2
                        }})

    layout = go.Layout(margin=go.layout.Margin(t=0, l=0, r=0, b=0))

    plotly.offline.plot(go.Figure([trace], layout),
                        filename='basic_sunburst_chart.html')
Пример #24
0
def updateFigIllit(sexe, disType, envir):
    global layout, my_colors, my_line_colors
    my_colors1 = copy.deepcopy(my_colors)
    my_colors1.append('rgb(199,255,184)')
    layout1 = copy.deepcopy(layout)
    layout1['title'] = "Analphabétisme par environnement "
    df = dfs_sum([illitSexeEnvir[dis].df for dis in disType]).loc[envir][sexe]
    if len(sexe) == 1:
        if len(envir) == 2:
            trace = go.Pie(labels=envir,
                           values=df.loc[envir[0]].tolist() +
                           df.loc[envir[1]].tolist(),
                           marker_colors=my_colors1,
                           hole=.3,
                           opacity=0.7)
        else:
            trace = trace = go.Pie(labels=sexe,
                                   values=df.loc[envir[0]].tolist(),
                                   marker_colors=my_colors1,
                                   hole=.3,
                                   opacity=0.7)
    else:
        if len(envir) == 2:
            trace = go.Sunburst(
                ids=[env for env in envir] +
                [env + " - " + sex for env in envir for sex in sexe],
                labels=[env for env in envir] + [sex for sex in sexe] * 2,
                parents=["" for i in range(len(envir))] +
                list(chain.from_iterable((env, env) for env in envir)),
                values=[df.loc[env].sum() for env in envir] +
                [df.loc[env][sex] for env in envir for sex in sexe],
                branchvalues="total",
                marker=dict(colors=my_colors, autocolorscale=True))
        else:
            layout1[
                'title'] = "Analphabétisme dans le monde " + envir[0].lower()
            trace = trace = go.Pie(labels=sexe,
                                   values=df.loc[envir[0]].tolist(),
                                   marker_colors=my_colors1,
                                   hole=.3,
                                   opacity=0.7)
    return {'data': [trace], 'layout': layout1}
Пример #25
0
def update_syllabus_sunburst(*args, **kwargs):
    callback = kwargs['callback_context']
    user = kwargs['user']
    students = get_students_from_graph(callback, user)

    sittings = set_sittings(callback, user)

    parent_point_pk = get_root_pk(callback)
    if not parent_point_pk:
        return False
    parent_point = Syllabus.objects.get(pk=parent_point_pk)
    points = parent_point.get_descendants(include_self=True)
    labels = [point.text for point in points]
    ids = [point.pk for point in points]
    parents = [point.parent.text for point in points]
    parents[0] = ""
    values = [1 for point in points]
    colors = [point.cohort_stats(students, sittings)['rating'] for point in points]

    graph = go.Sunburst(
        labels=labels,
        parents=parents,
        values=values,
        customdata=ids,
        marker=dict(colors=colors,
                    colorscale='RdYlGn',
                    cmid=2.5,
                    cmax=5,
                    cmin=0),
        hovertemplate='<b>%{label}</b><br>Average rating: %{color}',
        name='',

    )
    layout = go.Layout(
        margin=dict(t=0, l=0, r=0, b=0),
        uniformtext=dict(minsize=10, mode='hide'),
        title='Syllabus Performance Explorer',
        showlegend=False

    )

    return {'data': [graph], 'layout': layout}
Пример #26
0
 def GetChartTrace(self):
     super().GetChartTrace()
     #pdb.set_trace()
     return [
         go.Sunburst(
             ids=self.DataFrame[self.labelCol],
             labels=self.DataFrame[self.labelCol],
             parents=self.DataFrame[self.parentCol],
             #branchvalues="total",
             #domain=dict(column=1)
             values=self.DataFrame[self.valCol],
             branchvalues="total",
             marker={
                 "line": {
                     "width": 2,
                     "color": "rgb(255,255,255)"
                 },
                 "colors": plotting["ColorSchemes"][selectedScheme]
             })
     ]
Пример #27
0
 def showExpand(self):
     labels = [str(self.total)]
     parents = [""]
     values = [self.total]
     for parent in self.dataParents:
         labels.append(parent[0])
         parents.append(str(self.total))
         values.append(parent[1])
     for child in self.dataChildren:
         if (child[0] in labels):
             totalParent = values[labels.index(child[0])]
             labels.append("{0}\n{1:.2f} %".format(
                 child[1], child[2] / totalParent * 100))
             parents.append(child[0])
             values.append(child[2])
     fig = go.Figure(
         go.Sunburst(
             labels=labels,
             parents=parents,
             values=values,
             branchvalues="total",
         ))
     self.show(fig, self.title)
Пример #28
0
def draw_skills():
    '''
    Draw the sunburst figure showing the entire skill
    tree

    Args:

    Returns:
        figure: The plotly figure showing all skills
    '''
    # Create the relationship vectors
    labels = []
    parents = []
    dict_to_lists(skills, labels, parents)

    # Plot
    data = [
        go.Sunburst(labels=labels,
                    parents=parents,
                    insidetextorientation='radial')
    ]

    # Layout
    layout = dict(title=dict(text='<b>My Skills</b>',
                             y=0.95,
                             x=0.5,
                             xanchor='center',
                             yanchor='top',
                             font=dict(family='Heebo', size=24,
                                       color='black')),
                  plot_bgcolor='rgba(0,0,0,0)',
                  paper_bgcolor='rgba(0,0,0,0)',
                  margin=dict(l=0, r=0, t=0, b=0))

    # Return
    figure = go.Figure(data=data, layout=layout)
    return figure
Пример #29
0
 def modifyCirclesBooks(self):
     bigdata = self.ddlBigData.currentText()
     if (bigdata != 'Selecciona un dato'):
         if (self.circleBooks >= 0):
             books = self.exec(QUERYBOOKS.format(bigdata))
             parents = [""] + self.getColumn(books, 0)
             names = [bigdata] + self.getColumn(books, 1)
             counts = self.getColumn(books, 2)
             total = self.getTotal(counts)
             values = [total] + counts
             if (self.circleBooks >= 1):
                 tables = self.exec(QUERYTABLES.format(bigdata))
                 parents = parents + self.getColumn(tables, 0)
                 newValues = self.getColumn(tables, 2)
                 if (self.circleBooks == 1):
                     names = names + \
                         self.getPercentages(self.getColumn(
                             tables, 1), newValues, total)
                 else:
                     names = names + self.getColumn(tables, 1)
                 values = values + newValues
             if (self.circleBooks >= 2):
                 fields = self.exec(QUERYFIELDS.format(bigdata))
                 parents = parents + self.getColumn(fields, 0)
                 newValues = self.getColumn(fields, 2)
                 names = names + \
                     self.getPercentages(self.getColumn(
                         fields, 1), newValues, total)
                 values = values + newValues
             fig = go.Figure(
                 go.Sunburst(
                     labels=names,
                     parents=parents,
                     values=values,
                     branchvalues="total",
                 ))
             self.show(fig, 'Residencia de {0}'.format(bigdata))
Пример #30
0
        # marker = {"colors":color},
    )
    #figsunburt=figsunburt.update_layout(margin = dict(t=0, l=0, r=0, b=0))
    return figsunburt

figsunburt2015=updatefigsunburt(l2015int)
figsunburt2016=updatefigsunburt(l2016int)
figsunburt2017=updatefigsunburt(l2017int)"""
figsunburt2015 = go.Figure(
    go.Sunburst(labels=[
        "Ariana", "Ben Arous", "Mannouba", "Tunis", "Grand Tunis", "Bizerte",
        "Nabeul", "Nord-Est", "Kairouan", "Centre-Ouest", "Mahdia", "Monastir",
        "Sfax", "Sousse", "Centre-Est", "Medenine", "Sud-Est", "Total"
    ],
                parents=[
                    "Grand Tunis", "Grand Tunis", "Grand Tunis", "Grand Tunis",
                    "Total", "Nord-Est", "Nord-Est", "Total", "Centre-Ouest",
                    "Total", "Centre-Est", "Centre-Est", "Centre-Est",
                    "Centre-Est", "Total", "Sud-Est", "Total", ""
                ],
                values=l2015int,
                branchvalues='total'))
figsunburt2015.update_layout(margin=dict(t=0, l=0, r=0, b=0))
figsunburt2016 = go.Figure(
    go.Sunburst(labels=[
        "Ariana", "Ben Arous", "Mannouba", "Tunis", "Grand Tunis", "Bizerte",
        "Nabeul", "Nord-Est", "Kairouan", "Centre-Ouest", "Mahdia", "Monastir",
        "Sfax", "Sousse", "Centre-Est", "Medenine", "Sud-Est", "Total"
    ],
                parents=[
                    "Grand Tunis", "Grand Tunis", "Grand Tunis", "Grand Tunis",