コード例 #1
0
def violin_colorscale(data, data_header, group_header, colors, use_colorscale,
                      group_stats, rugplot, sort, height, width,
                      title):
    """
    Refer to FigureFactory.create_violin() for docstring.

    Returns fig for violin plot with colorscale.

    """

    # collect all group names
    group_name = []
    for name in data[group_header]:
        if name not in group_name:
            group_name.append(name)
    if sort:
        group_name.sort()

    # make sure all group names are keys in group_stats
    for group in group_name:
        if group not in group_stats:
            raise exceptions.PlotlyError("All values/groups in the index "
                                         "column must be represented "
                                         "as a key in group_stats.")

    gb = data.groupby([group_header])

    group_name = list(gb.median().sort_values(data_header,
                                         ascending=False).index)
    L = len(group_name)


    fig = make_subplots(rows=1, cols=L,
                        shared_yaxes=True,
                        horizontal_spacing=0.025,
                        print_grid=False)

    # prepare low and high color for colorscale
    lowcolor = utils.color_parser(colors[0], utils.unlabel_rgb)
    highcolor = utils.color_parser(colors[1], utils.unlabel_rgb)

    # find min and max values in group_stats
    group_stats_values = []
    for key in group_stats:
        group_stats_values.append(group_stats[key])

    max_value = max(group_stats_values)
    min_value = min(group_stats_values)

    for k, gr in enumerate(group_name):
        vals = np.asarray(gb.get_group(gr)[data_header], np.float)

        # find intermediate color from colorscale
        intermed = (group_stats[gr] - min_value) / (max_value - min_value)
        intermed_color = utils.find_intermediate_color(
            lowcolor, highcolor, intermed
        )

        plot_data, plot_xrange = violinplot(
            vals,
            fillcolor='rgb{}'.format(intermed_color),
            rugplot=rugplot
        )
        layout = graph_objs.Layout()

        for item in plot_data:
            fig.append_trace(item, 1, k + 1)
        fig['layout'].update(
            {'xaxis{}'.format(k + 1): make_XAxis(group_name[k], plot_xrange)}
        )
    # add colorbar to plot
    trace_dummy = graph_objs.Scatter(
        x=[0],
        y=[0],
        mode='markers',
        marker=dict(
            size=2,
            cmin=min_value,
            cmax=max_value,
            colorscale=[[0, colors[0]],
                        [1, colors[1]]],
            showscale=True),
        showlegend=False,
    )
    fig.append_trace(trace_dummy, 1, L)

    # set the sharey axis style
    fig['layout'].update({'yaxis{}'.format(1): make_YAxis(data_header)})
    fig['layout'].update(
        title=title,
        showlegend=False,
        hovermode='closest',
        autosize=True,
        height=height,
        margin=graph_objs.Margin(l=50, b=100)
    )

    return fig
コード例 #2
0
ファイル: _gantt.py プロジェクト: kasunsp/pinalpha_mvp
def gantt_colorscale(chart,
                     colors,
                     title,
                     index_col,
                     show_colorbar,
                     bar_width,
                     showgrid_x,
                     showgrid_y,
                     height,
                     width,
                     tasks=None,
                     task_names=None,
                     data=None,
                     group_tasks=False):
    """
    Refer to FigureFactory.create_gantt() for docstring
    """
    if tasks is None:
        tasks = []
    if task_names is None:
        task_names = []
    if data is None:
        data = []
    showlegend = False

    for index in range(len(chart)):
        task = dict(x0=chart[index]['Start'],
                    x1=chart[index]['Finish'],
                    name=chart[index]['Task'])
        if 'Description' in chart[index]:
            task['description'] = chart[index]['Description']
        tasks.append(task)

    shape_template = {
        'type': 'rect',
        'xref': 'x',
        'yref': 'y',
        'opacity': 1,
        'line': {
            'width': 0,
        }
    }

    # compute the color for task based on indexing column
    if isinstance(chart[0][index_col], Number):
        # check that colors has at least 2 colors
        if len(colors) < 2:
            raise exceptions.PlotlyError(
                "You must use at least 2 colors in 'colors' if you "
                "are using a colorscale. However only the first two "
                "colors given will be used for the lower and upper "
                "bounds on the colormap.")

        # create the list of task names
        for index in range(len(tasks)):
            tn = tasks[index]['name']
            # Is added to task_names if group_tasks is set to False,
            # or if the option is used (True) it only adds them if the
            # name is not already in the list
            if not group_tasks or tn not in task_names:
                task_names.append(tn)
        # Guarantees that for grouped tasks the tasks that are inserted
        # first are shown at the top
        if group_tasks:
            task_names.reverse()

        for index in range(len(tasks)):
            tn = tasks[index]['name']
            del tasks[index]['name']
            tasks[index].update(shape_template)

            # If group_tasks is True, all tasks with the same name belong
            # to the same row.
            groupID = index
            if group_tasks:
                groupID = task_names.index(tn)
            tasks[index]['y0'] = groupID - bar_width
            tasks[index]['y1'] = groupID + bar_width

            # unlabel color
            colors = utils.color_parser(colors, utils.unlabel_rgb)
            lowcolor = colors[0]
            highcolor = colors[1]

            intermed = (chart[index][index_col]) / 100.0
            intermed_color = utils.find_intermediate_color(
                lowcolor, highcolor, intermed)
            intermed_color = utils.color_parser(intermed_color,
                                                utils.label_rgb)
            tasks[index]['fillcolor'] = intermed_color
            # relabel colors with 'rgb'
            colors = utils.color_parser(colors, utils.label_rgb)

            # add a line for hover text and autorange
            entry = dict(x=[tasks[index]['x0'], tasks[index]['x1']],
                         y=[groupID, groupID],
                         name='',
                         marker={'color': 'white'})
            if "description" in tasks[index]:
                entry['text'] = tasks[index]['description']
                del tasks[index]['description']
            data.append(entry)

        if show_colorbar is True:
            # generate dummy data for colorscale visibility
            data.append(
                dict(x=[tasks[index]['x0'], tasks[index]['x0']],
                     y=[index, index],
                     name='',
                     marker={
                         'color': 'white',
                         'colorscale': [[0, colors[0]], [1, colors[1]]],
                         'showscale': True,
                         'cmax': 100,
                         'cmin': 0
                     }))

    if isinstance(chart[0][index_col], str):
        index_vals = []
        for row in range(len(tasks)):
            if chart[row][index_col] not in index_vals:
                index_vals.append(chart[row][index_col])

        index_vals.sort()

        if len(colors) < len(index_vals):
            raise exceptions.PlotlyError(
                "Error. The number of colors in 'colors' must be no less "
                "than the number of unique index values in your group "
                "column.")

        # make a dictionary assignment to each index value
        index_vals_dict = {}
        # define color index
        c_index = 0
        for key in index_vals:
            if c_index > len(colors) - 1:
                c_index = 0
            index_vals_dict[key] = colors[c_index]
            c_index += 1

        # create the list of task names
        for index in range(len(tasks)):
            tn = tasks[index]['name']
            # Is added to task_names if group_tasks is set to False,
            # or if the option is used (True) it only adds them if the
            # name is not already in the list
            if not group_tasks or tn not in task_names:
                task_names.append(tn)
        # Guarantees that for grouped tasks the tasks that are inserted
        # first are shown at the top
        if group_tasks:
            task_names.reverse()

        for index in range(len(tasks)):
            tn = tasks[index]['name']
            del tasks[index]['name']
            tasks[index].update(shape_template)
            # If group_tasks is True, all tasks with the same name belong
            # to the same row.
            groupID = index
            if group_tasks:
                groupID = task_names.index(tn)
            tasks[index]['y0'] = groupID - bar_width
            tasks[index]['y1'] = groupID + bar_width

            tasks[index]['fillcolor'] = index_vals_dict[chart[index]
                                                        [index_col]]

            # add a line for hover text and autorange
            entry = dict(x=[tasks[index]['x0'], tasks[index]['x1']],
                         y=[groupID, groupID],
                         name='',
                         marker={'color': 'white'})
            if "description" in tasks[index]:
                entry['text'] = tasks[index]['description']
                del tasks[index]['description']
            data.append(entry)

        if show_colorbar is True:
            # generate dummy data to generate legend
            showlegend = True
            for k, index_value in enumerate(index_vals):
                data.append(
                    dict(x=[tasks[index]['x0'], tasks[index]['x0']],
                         y=[k, k],
                         showlegend=True,
                         name=str(index_value),
                         hoverinfo='none',
                         marker=dict(color=colors[k], size=1)))

    layout = dict(
        title=title,
        showlegend=showlegend,
        height=height,
        width=width,
        shapes=[],
        hovermode='closest',
        yaxis=dict(
            showgrid=showgrid_y,
            ticktext=task_names,
            tickvals=list(range(len(task_names))),
            range=[-1, len(task_names) + 1],
            autorange=False,
            zeroline=False,
        ),
        xaxis=dict(
            showgrid=showgrid_x,
            zeroline=False,
            rangeselector=dict(buttons=list([
                dict(count=7, label='1w', step='day', stepmode='backward'),
                dict(count=1, label='1m', step='month', stepmode='backward'),
                dict(count=6, label='6m', step='month', stepmode='backward'),
                dict(count=1, label='YTD', step='year', stepmode='todate'),
                dict(count=1, label='1y', step='year', stepmode='backward'),
                dict(step='all')
            ])),
            type='date'))
    layout['shapes'] = tasks

    fig = dict(data=data, layout=layout)
    return fig
コード例 #3
0
ファイル: _violin.py プロジェクト: mode/plotly.py
def violin_colorscale(data, data_header, group_header, colors, use_colorscale,
                      group_stats, rugplot, sort, height, width,
                      title):
    """
    Refer to FigureFactory.create_violin() for docstring.

    Returns fig for violin plot with colorscale.

    """

    # collect all group names
    group_name = []
    for name in data[group_header]:
        if name not in group_name:
            group_name.append(name)
    if sort:
        group_name.sort()

    # make sure all group names are keys in group_stats
    for group in group_name:
        if group not in group_stats:
            raise exceptions.PlotlyError("All values/groups in the index "
                                         "column must be represented "
                                         "as a key in group_stats.")

    gb = data.groupby([group_header])
    L = len(group_name)

    fig = make_subplots(rows=1, cols=L,
                        shared_yaxes=True,
                        horizontal_spacing=0.025,
                        print_grid=False)

    # prepare low and high color for colorscale
    lowcolor = utils.color_parser(colors[0], utils.unlabel_rgb)
    highcolor = utils.color_parser(colors[1], utils.unlabel_rgb)

    # find min and max values in group_stats
    group_stats_values = []
    for key in group_stats:
        group_stats_values.append(group_stats[key])

    max_value = max(group_stats_values)
    min_value = min(group_stats_values)

    for k, gr in enumerate(group_name):
        vals = np.asarray(gb.get_group(gr)[data_header], np.float)

        # find intermediate color from colorscale
        intermed = (group_stats[gr] - min_value) / (max_value - min_value)
        intermed_color = utils.find_intermediate_color(
            lowcolor, highcolor, intermed
        )

        plot_data, plot_xrange = violinplot(
            vals,
            fillcolor='rgb{}'.format(intermed_color),
            rugplot=rugplot
        )
        layout = graph_objs.Layout()

        for item in plot_data:
            fig.append_trace(item, 1, k + 1)
        fig['layout'].update(
            {'xaxis{}'.format(k + 1): make_XAxis(group_name[k], plot_xrange)}
        )
    # add colorbar to plot
    trace_dummy = graph_objs.Scatter(
        x=[0],
        y=[0],
        mode='markers',
        marker=dict(
            size=2,
            cmin=min_value,
            cmax=max_value,
            colorscale=[[0, colors[0]],
                        [1, colors[1]]],
            showscale=True),
        showlegend=False,
    )
    fig.append_trace(trace_dummy, 1, L)

    # set the sharey axis style
    fig['layout'].update({'yaxis{}'.format(1): make_YAxis('')})
    fig['layout'].update(
        title=title,
        showlegend=False,
        hovermode='closest',
        autosize=False,
        height=height,
        width=width
    )

    return fig
コード例 #4
0
ファイル: _gantt.py プロジェクト: mode/plotly.py
def gantt_colorscale(chart, colors, title, index_col, show_colorbar, bar_width,
                     showgrid_x, showgrid_y, height, width, tasks=None,
                     task_names=None, data=None, group_tasks=False):
    """
    Refer to FigureFactory.create_gantt() for docstring
    """
    if tasks is None:
        tasks = []
    if task_names is None:
        task_names = []
    if data is None:
        data = []
    showlegend = False

    for index in range(len(chart)):
        task = dict(x0=chart[index]['Start'],
                    x1=chart[index]['Finish'],
                    name=chart[index]['Task'])
        if 'Description' in chart[index]:
            task['description'] = chart[index]['Description']
        tasks.append(task)

    shape_template = {
        'type': 'rect',
        'xref': 'x',
        'yref': 'y',
        'opacity': 1,
        'line': {
            'width': 0,
        }
    }

    # compute the color for task based on indexing column
    if isinstance(chart[0][index_col], Number):
        # check that colors has at least 2 colors
        if len(colors) < 2:
            raise exceptions.PlotlyError(
                "You must use at least 2 colors in 'colors' if you "
                "are using a colorscale. However only the first two "
                "colors given will be used for the lower and upper "
                "bounds on the colormap."
            )

        # create the list of task names
        for index in range(len(tasks)):
            tn = tasks[index]['name']
            # Is added to task_names if group_tasks is set to False,
            # or if the option is used (True) it only adds them if the
            # name is not already in the list
            if not group_tasks or tn not in task_names:
                task_names.append(tn)
        # Guarantees that for grouped tasks the tasks that are inserted
        # first are shown at the top
        if group_tasks:
            task_names.reverse()

        for index in range(len(tasks)):
            tn = tasks[index]['name']
            del tasks[index]['name']
            tasks[index].update(shape_template)

            # If group_tasks is True, all tasks with the same name belong
            # to the same row.
            groupID = index
            if group_tasks:
                groupID = task_names.index(tn)
            tasks[index]['y0'] = groupID - bar_width
            tasks[index]['y1'] = groupID + bar_width

            # unlabel color
            colors = utils.color_parser(colors, utils.unlabel_rgb)
            lowcolor = colors[0]
            highcolor = colors[1]

            intermed = (chart[index][index_col]) / 100.0
            intermed_color = utils.find_intermediate_color(
                lowcolor, highcolor, intermed
            )
            intermed_color = utils.color_parser(
                intermed_color, utils.label_rgb
            )
            tasks[index]['fillcolor'] = intermed_color
            # relabel colors with 'rgb'
            colors = utils.color_parser(colors, utils.label_rgb)

            # add a line for hover text and autorange
            entry = dict(
                x=[tasks[index]['x0'], tasks[index]['x1']],
                y=[groupID, groupID],
                name='',
                marker={'color': 'white'}
            )
            if "description" in tasks[index]:
                entry['text'] = tasks[index]['description']
                del tasks[index]['description']
            data.append(entry)

        if show_colorbar is True:
            # generate dummy data for colorscale visibility
            data.append(
                dict(
                    x=[tasks[index]['x0'], tasks[index]['x0']],
                    y=[index, index],
                    name='',
                    marker={'color': 'white',
                            'colorscale': [[0, colors[0]], [1, colors[1]]],
                            'showscale': True,
                            'cmax': 100,
                            'cmin': 0}
                )
            )

    if isinstance(chart[0][index_col], str):
        index_vals = []
        for row in range(len(tasks)):
            if chart[row][index_col] not in index_vals:
                index_vals.append(chart[row][index_col])

        index_vals.sort()

        if len(colors) < len(index_vals):
            raise exceptions.PlotlyError(
                "Error. The number of colors in 'colors' must be no less "
                "than the number of unique index values in your group "
                "column."
            )

        # make a dictionary assignment to each index value
        index_vals_dict = {}
        # define color index
        c_index = 0
        for key in index_vals:
            if c_index > len(colors) - 1:
                c_index = 0
            index_vals_dict[key] = colors[c_index]
            c_index += 1

        # create the list of task names
        for index in range(len(tasks)):
            tn = tasks[index]['name']
            # Is added to task_names if group_tasks is set to False,
            # or if the option is used (True) it only adds them if the
            # name is not already in the list
            if not group_tasks or tn not in task_names:
                task_names.append(tn)
        # Guarantees that for grouped tasks the tasks that are inserted
        # first are shown at the top
        if group_tasks:
            task_names.reverse()

        for index in range(len(tasks)):
            tn = tasks[index]['name']
            del tasks[index]['name']
            tasks[index].update(shape_template)
            # If group_tasks is True, all tasks with the same name belong
            # to the same row.
            groupID = index
            if group_tasks:
                groupID = task_names.index(tn)
            tasks[index]['y0'] = groupID - bar_width
            tasks[index]['y1'] = groupID + bar_width

            tasks[index]['fillcolor'] = index_vals_dict[
                chart[index][index_col]
            ]

            # add a line for hover text and autorange
            entry = dict(
                x=[tasks[index]['x0'], tasks[index]['x1']],
                y=[groupID, groupID],
                name='',
                marker={'color': 'white'}
            )
            if "description" in tasks[index]:
                entry['text'] = tasks[index]['description']
                del tasks[index]['description']
            data.append(entry)

        if show_colorbar is True:
            # generate dummy data to generate legend
            showlegend = True
            for k, index_value in enumerate(index_vals):
                data.append(
                    dict(
                        x=[tasks[index]['x0'], tasks[index]['x0']],
                        y=[k, k],
                        showlegend=True,
                        name=str(index_value),
                        hoverinfo='none',
                        marker=dict(
                            color=colors[k],
                            size=1
                        )
                    )
                )

    layout = dict(
        title=title,
        showlegend=showlegend,
        height=height,
        width=width,
        shapes=[],
        hovermode='closest',
        yaxis=dict(
            showgrid=showgrid_y,
            ticktext=task_names,
            tickvals=list(range(len(task_names))),
            range=[-1, len(task_names) + 1],
            autorange=False,
            zeroline=False,
        ),
        xaxis=dict(
            showgrid=showgrid_x,
            zeroline=False,
            rangeselector=dict(
                buttons=list([
                    dict(count=7,
                         label='1w',
                         step='day',
                         stepmode='backward'),
                    dict(count=1,
                         label='1m',
                         step='month',
                         stepmode='backward'),
                    dict(count=6,
                         label='6m',
                         step='month',
                         stepmode='backward'),
                    dict(count=1,
                         label='YTD',
                         step='year',
                         stepmode='todate'),
                    dict(count=1,
                         label='1y',
                         step='year',
                         stepmode='backward'),
                    dict(step='all')
                ])
            ),
            type='date'
        )
    )
    layout['shapes'] = tasks

    fig = dict(data=data, layout=layout)
    return fig