Exemplo n.º 1
0
def violin_dict(
    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 without 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()

    # check if all group names appear in colors dict
    for group in group_name:
        if group not in colors:
            raise exceptions.PlotlyError("If colors is a dictionary, all "
                                         "the group names must appear as "
                                         "keys in colors.")

    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)

    for k, gr in enumerate(group_name):
        vals = np.asarray(gb.get_group(gr)[data_header], np.float)
        plot_data, plot_xrange = violinplot(vals,
                                            fillcolor=colors[gr],
                                            rugplot=rugplot)
        layout = graph_objs.Layout()

        for item in plot_data:
            fig.append_trace(item, 1, k + 1)

        # add violin plot labels
        fig["layout"].update(
            {"xaxis{}".format(k + 1): make_XAxis(group_name[k], plot_xrange)})

    # 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
Exemplo n.º 2
0
def create_violin(
    data,
    data_header=None,
    group_header=None,
    colors=None,
    use_colorscale=False,
    group_stats=None,
    rugplot=True,
    sort=False,
    height=450,
    width=600,
    title="Violin and Rug Plot",
):
    """
    Returns figure for a violin plot

    :param (list|array) data: accepts either a list of numerical values,
        a list of dictionaries all with identical keys and at least one
        column of numeric values, or a pandas dataframe with at least one
        column of numbers.
    :param (str) data_header: the header of the data column to be used
        from an inputted pandas dataframe. Not applicable if 'data' is
        a list of numeric values.
    :param (str) group_header: applicable if grouping data by a variable.
        'group_header' must be set to the name of the grouping variable.
    :param (str|tuple|list|dict) colors: either a plotly scale name,
        an rgb or hex color, a color tuple, a list of colors or a
        dictionary. An rgb color is of the form 'rgb(x, y, z)' where
        x, y and z belong to the interval [0, 255] and a color tuple is a
        tuple of the form (a, b, c) where a, b and c belong to [0, 1].
        If colors is a list, it must contain valid color types as its
        members.
    :param (bool) use_colorscale: only applicable if grouping by another
        variable. Will implement a colorscale based on the first 2 colors
        of param colors. This means colors must be a list with at least 2
        colors in it (Plotly colorscales are accepted since they map to a
        list of two rgb colors). Default = False
    :param (dict) group_stats: a dictioanry where each key is a unique
        value from the group_header column in data. Each value must be a
        number and will be used to color the violin plots if a colorscale
        is being used.
    :param (bool) rugplot: determines if a rugplot is draw on violin plot.
        Default = True
    :param (bool) sort: determines if violins are sorted
        alphabetically (True) or by input order (False). Default = False
    :param (float) height: the height of the violin plot.
    :param (float) width: the width of the violin plot.
    :param (str) title: the title of the violin plot.

    Example 1: Single Violin Plot

    >>> from plotly_study.figure_factory import create_violin
    >>> import plotly_study.graph_objs as graph_objects

    >>> import numpy as np
    >>> from scipy import stats

    >>> # create list of random values
    >>> data_list = np.random.randn(100)
    >>> data_list.tolist()

    >>> # create violin fig
    >>> fig = create_violin(data_list, colors='#604d9e')

    >>> # plot
    >>> fig.show()

    Example 2: Multiple Violin Plots with Qualitative Coloring

    >>> from plotly_study.figure_factory import create_violin
    >>> import plotly_study.graph_objs as graph_objects

    >>> import numpy as np
    >>> import pandas as pd
    >>> from scipy import stats

    >>> # create dataframe
    >>> np.random.seed(619517)
    >>> Nr=250
    >>> y = np.random.randn(Nr)
    >>> gr = np.random.choice(list("ABCDE"), Nr)
    >>> norm_params=[(0, 1.2), (0.7, 1), (-0.5, 1.4), (0.3, 1), (0.8, 0.9)]

    >>> for i, letter in enumerate("ABCDE"):
    ...     y[gr == letter] *=norm_params[i][1]+ norm_params[i][0]
    >>> df = pd.DataFrame(dict(Score=y, Group=gr))

    >>> # create violin fig
    >>> fig = create_violin(df, data_header='Score', group_header='Group',
    ...                    sort=True, height=600, width=1000)

    >>> # plot
    >>> fig.show()

    Example 3: Violin Plots with Colorscale

    >>> from plotly_study.figure_factory import create_violin
    >>> import plotly_study.graph_objs as graph_objects

    >>> import numpy as np
    >>> import pandas as pd
    >>> from scipy import stats

    >>> # create dataframe
    >>> np.random.seed(619517)
    >>> Nr=250
    >>> y = np.random.randn(Nr)
    >>> gr = np.random.choice(list("ABCDE"), Nr)
    >>> norm_params=[(0, 1.2), (0.7, 1), (-0.5, 1.4), (0.3, 1), (0.8, 0.9)]

    >>> for i, letter in enumerate("ABCDE"):
    ...     y[gr == letter] *=norm_params[i][1]+ norm_params[i][0]
    >>> df = pd.DataFrame(dict(Score=y, Group=gr))

    >>> # define header params
    >>> data_header = 'Score'
    >>> group_header = 'Group'

    >>> # make groupby object with pandas
    >>> group_stats = {}
    >>> groupby_data = df.groupby([group_header])

    >>> for group in "ABCDE":
    ...     data_from_group = groupby_data.get_group(group)[data_header]
    ...     # take a stat of the grouped data
    ...     stat = np.median(data_from_group)
    ...     # add to dictionary
    ...     group_stats[group] = stat

    >>> # create violin fig
    >>> fig = create_violin(df, data_header='Score', group_header='Group',
    ...                     height=600, width=1000, use_colorscale=True,
    ...                     group_stats=group_stats)

    >>> # plot
    >>> fig.show()
    """

    # Validate colors
    if isinstance(colors, dict):
        valid_colors = clrs.validate_colors_dict(colors, "rgb")
    else:
        valid_colors = clrs.validate_colors(colors, "rgb")

    # validate data and choose plot type
    if group_header is None:
        if isinstance(data, list):
            if len(data) <= 0:
                raise exceptions.PlotlyError("If data is a list, it must be "
                                             "nonempty and contain either "
                                             "numbers or dictionaries.")

            if not all(isinstance(element, Number) for element in data):
                raise exceptions.PlotlyError("If data is a list, it must "
                                             "contain only numbers.")

        if pd and isinstance(data, pd.core.frame.DataFrame):
            if data_header is None:
                raise exceptions.PlotlyError("data_header must be the "
                                             "column name with the "
                                             "desired numeric data for "
                                             "the violin plot.")

            data = data[data_header].values.tolist()

        # call the plotting functions
        plot_data, plot_xrange = violinplot(data,
                                            fillcolor=valid_colors[0],
                                            rugplot=rugplot)

        layout = graph_objs.Layout(
            title=title,
            autosize=False,
            font=graph_objs.layout.Font(size=11),
            height=height,
            showlegend=False,
            width=width,
            xaxis=make_XAxis("", plot_xrange),
            yaxis=make_YAxis(""),
            hovermode="closest",
        )
        layout["yaxis"].update(
            dict(showline=False, showticklabels=False, ticks=""))

        fig = graph_objs.Figure(data=plot_data, layout=layout)

        return fig

    else:
        if not isinstance(data, pd.core.frame.DataFrame):
            raise exceptions.PlotlyError("Error. You must use a pandas "
                                         "DataFrame if you are using a "
                                         "group header.")

        if data_header is None:
            raise exceptions.PlotlyError("data_header must be the column "
                                         "name with the desired numeric "
                                         "data for the violin plot.")

        if use_colorscale is False:
            if isinstance(valid_colors, dict):
                # validate colors dict choice below
                fig = violin_dict(
                    data,
                    data_header,
                    group_header,
                    valid_colors,
                    use_colorscale,
                    group_stats,
                    rugplot,
                    sort,
                    height,
                    width,
                    title,
                )
                return fig
            else:
                fig = violin_no_colorscale(
                    data,
                    data_header,
                    group_header,
                    valid_colors,
                    use_colorscale,
                    group_stats,
                    rugplot,
                    sort,
                    height,
                    width,
                    title,
                )
                return fig
        else:
            if isinstance(valid_colors, dict):
                raise exceptions.PlotlyError("The colors param cannot be "
                                             "a dictionary if you are "
                                             "using a colorscale.")

            if len(valid_colors) < 2:
                raise exceptions.PlotlyError("colors must be a list with "
                                             "at least 2 colors. A "
                                             "Plotly scale is allowed.")

            if not isinstance(group_stats, dict):
                raise exceptions.PlotlyError("Your group_stats param "
                                             "must be a dictionary.")

            fig = violin_colorscale(
                data,
                data_header,
                group_header,
                valid_colors,
                use_colorscale,
                group_stats,
                rugplot,
                sort,
                height,
                width,
                title,
            )
            return fig
Exemplo n.º 3
0
def create_ohlc(open,
                high,
                low,
                close,
                dates=None,
                direction="both",
                **kwargs):
    """
    BETA function that creates an ohlc chart

    :param (list) open: opening values
    :param (list) high: high values
    :param (list) low: low values
    :param (list) close: closing
    :param (list) dates: list of datetime objects. Default: None
    :param (string) direction: direction can be 'increasing', 'decreasing',
        or 'both'. When the direction is 'increasing', the returned figure
        consists of all units where the close value is greater than the
        corresponding open value, and when the direction is 'decreasing',
        the returned figure consists of all units where the close value is
        less than or equal to the corresponding open value. When the
        direction is 'both', both increasing and decreasing units are
        returned. Default: 'both'
    :param kwargs: kwargs passed through plotly_study.graph_objs.Scatter.
        These kwargs describe other attributes about the ohlc Scatter trace
        such as the color or the legend name. For more information on valid
        kwargs call help(plotly_study.graph_objs.Scatter)

    :rtype (dict): returns a representation of an ohlc chart figure.

    Example 1: Simple OHLC chart from a Pandas DataFrame

    >>> from plotly_study.figure_factory import create_ohlc
    >>> from datetime import datetime

    >>> import pandas.io.data as web

    >>> df = web.DataReader("aapl", 'yahoo', datetime(2008, 8, 15),
    ...                     datetime(2008, 10, 15))
    >>> fig = create_ohlc(df.Open, df.High, df.Low, df.Close, dates=df.index)
    >>> fig.show()

    Example 2: Add text and annotations to the OHLC chart

    >>> from plotly_study.figure_factory import create_ohlc
    >>> from datetime import datetime

    >>> import pandas.io.data as web

    >>> df = web.datareader("aapl", 'yahoo', datetime(2008, 8, 15),
    ...                     datetime(2008, 10, 15))
    >>> fig = create_ohlc(df.open, df.high, df.low, df.close, dates=df.index)

    >>> # update the fig - options here: https://plot.ly/python/reference/#layout
    >>> fig['layout'].update({
    ...     'title': 'the great recession',
    ...     'yaxis': {'title': 'aapl stock'},
    ...     'shapes': [{
    ...         'x0': '2008-09-15', 'x1': '2008-09-15', 'type': 'line',
    ...         'y0': 0, 'y1': 1, 'xref': 'x', 'yref': 'paper',
    ...         'line': {'color': 'rgb(40,40,40)', 'width': 0.5}
    ...     }],
    ...     'annotations': [{
    ...         'text': "the fall of lehman brothers",
    ...         'x': '2008-09-15', 'y': 1.02,
    ...         'xref': 'x', 'yref': 'paper',
    ...         'showarrow': false, 'xanchor': 'left'
    ...     }]
    ... })
    >>> fig.show()

    Example 3: Customize the OHLC colors

    >>> from plotly_study.figure_factory import create_ohlc
    >>> from plotly_study.graph_objs import Line, Marker
    >>> from datetime import datetime

    >>> import pandas.io.data as web

    >>> df = web.DataReader("aapl", 'yahoo', datetime(2008, 1, 1),
    ...                     datetime(2009, 4, 1))

    >>> # Make increasing ohlc sticks and customize their color and name
    >>> fig_increasing = create_ohlc(df.Open, df.High, df.Low, df.Close,
    ...                              dates=df.index, direction='increasing',
    ...                              name='AAPL',
    ...                              line=Line(color='rgb(150, 200, 250)'))

    >>> # Make decreasing ohlc sticks and customize their color and name
    >>> fig_decreasing = create_ohlc(df.Open, df.High, df.Low, df.Close,
    ...                              dates=df.index, direction='decreasing',
    ...                              line=Line(color='rgb(128, 128, 128)'))

    >>> # Initialize the figure
    >>> fig = fig_increasing

    >>> # Add decreasing data with .extend()
    >>> fig['data'].extend(fig_decreasing['data'])
    >>> fig.show()


    Example 4: OHLC chart with datetime objects

    >>> from plotly_study.figure_factory import create_ohlc

    >>> from datetime import datetime

    >>> # Add data
    >>> open_data = [33.0, 33.3, 33.5, 33.0, 34.1]
    >>> high_data = [33.1, 33.3, 33.6, 33.2, 34.8]
    >>> low_data = [32.7, 32.7, 32.8, 32.6, 32.8]
    >>> close_data = [33.0, 32.9, 33.3, 33.1, 33.1]
    >>> dates = [datetime(year=2013, month=10, day=10),
    ...          datetime(year=2013, month=11, day=10),
    ...          datetime(year=2013, month=12, day=10),
    ...          datetime(year=2014, month=1, day=10),
    ...          datetime(year=2014, month=2, day=10)]

    >>> # Create ohlc
    >>> fig = create_ohlc(open_data, high_data, low_data, close_data, dates=dates)
    >>> fig.show()
    """
    if dates is not None:
        utils.validate_equal_length(open, high, low, close, dates)
    else:
        utils.validate_equal_length(open, high, low, close)
    validate_ohlc(open, high, low, close, direction, **kwargs)

    if direction is "increasing":
        ohlc_incr = make_increasing_ohlc(open, high, low, close, dates,
                                         **kwargs)
        data = [ohlc_incr]
    elif direction is "decreasing":
        ohlc_decr = make_decreasing_ohlc(open, high, low, close, dates,
                                         **kwargs)
        data = [ohlc_decr]
    else:
        ohlc_incr = make_increasing_ohlc(open, high, low, close, dates,
                                         **kwargs)
        ohlc_decr = make_decreasing_ohlc(open, high, low, close, dates,
                                         **kwargs)
        data = [ohlc_incr, ohlc_decr]

    layout = graph_objs.Layout(xaxis=dict(zeroline=False), hovermode="closest")

    return graph_objs.Figure(data=data, layout=layout)
Exemplo n.º 4
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])
    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 = clrs.color_parser(colors[0], clrs.unlabel_rgb)
    highcolor = clrs.color_parser(colors[1], clrs.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 = clrs.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
Exemplo n.º 5
0
def create_candlestick(open,
                       high,
                       low,
                       close,
                       dates=None,
                       direction="both",
                       **kwargs):
    """
    BETA function that creates a candlestick chart

    :param (list) open: opening values
    :param (list) high: high values
    :param (list) low: low values
    :param (list) close: closing values
    :param (list) dates: list of datetime objects. Default: None
    :param (string) direction: direction can be 'increasing', 'decreasing',
        or 'both'. When the direction is 'increasing', the returned figure
        consists of all candlesticks where the close value is greater than
        the corresponding open value, and when the direction is
        'decreasing', the returned figure consists of all candlesticks
        where the close value is less than or equal to the corresponding
        open value. When the direction is 'both', both increasing and
        decreasing candlesticks are returned. Default: 'both'
    :param kwargs: kwargs passed through plotly_study.graph_objs.Scatter.
        These kwargs describe other attributes about the ohlc Scatter trace
        such as the color or the legend name. For more information on valid
        kwargs call help(plotly_study.graph_objs.Scatter)

    :rtype (dict): returns a representation of candlestick chart figure.

    Example 1: Simple candlestick chart from a Pandas DataFrame

    >>> from plotly_study.figure_factory import create_candlestick
    >>> from datetime import datetime

    >>> import pandas.io.data as web

    >>> df = web.DataReader("aapl", 'yahoo', datetime(2007, 10, 1), datetime(2009, 4, 1))
    >>> fig = create_candlestick(df.Open, df.High, df.Low, df.Close, dates=df.index)
    >>> fig.show()

    Example 2: Add text and annotations to the candlestick chart
    
    >>> fig = create_candlestick(df.Open, df.High, df.Low, df.Close, dates=df.index)
    >>> # Update the fig - all options here: https://plot.ly/python/reference/#Layout
    >>> fig['layout'].update({
        'title': 'The Great Recession',
        'yaxis': {'title': 'AAPL Stock'},
        'shapes': [{
            'x0': '2007-12-01', 'x1': '2007-12-01',
            'y0': 0, 'y1': 1, 'xref': 'x', 'yref': 'paper',
            'line': {'color': 'rgb(30,30,30)', 'width': 1}
        }],
        'annotations': [{
            'x': '2007-12-01', 'y': 0.05, 'xref': 'x', 'yref': 'paper',
            'showarrow': False, 'xanchor': 'left',
            'text': 'Official start of the recession'
        }]
    })
    >>> fig.show()

    Example 3: Customize the candlestick colors
    
    >>> from plotly_study.figure_factory import create_candlestick
    >>> from plotly_study.graph_objs import Line, Marker
    >>> from datetime import datetime

    >>> import pandas.io.data as web

    >>> df = web.DataReader("aapl", 'yahoo', datetime(2008, 1, 1), datetime(2009, 4, 1))

    >>> # Make increasing candlesticks and customize their color and name
    >>> fig_increasing = create_candlestick(df.Open, df.High, df.Low, df.Close, dates=df.index,
    ...     direction='increasing', name='AAPL',
    ...     marker=Marker(color='rgb(150, 200, 250)'),
    ...     line=Line(color='rgb(150, 200, 250)'))

    >>> # Make decreasing candlesticks and customize their color and name
    >>> fig_decreasing = create_candlestick(df.Open, df.High, df.Low, df.Close, dates=df.index,
    ...     direction='decreasing',
    ...     marker=Marker(color='rgb(128, 128, 128)'),
    ...     line=Line(color='rgb(128, 128, 128)'))

    >>> # Initialize the figure
    >>> fig = fig_increasing

    >>> # Add decreasing data with .extend()
    >>> fig['data'].extend(fig_decreasing['data'])
    >>> fig.show()

    Example 4: Candlestick chart with datetime objects
    
    >>> from plotly_study.figure_factory import create_candlestick

    >>> from datetime import datetime

    >>> # Add data
    >>> open_data = [33.0, 33.3, 33.5, 33.0, 34.1]
    >>> high_data = [33.1, 33.3, 33.6, 33.2, 34.8]
    >>> low_data = [32.7, 32.7, 32.8, 32.6, 32.8]
    >>> close_data = [33.0, 32.9, 33.3, 33.1, 33.1]
    >>> dates = [datetime(year=2013, month=10, day=10),
    ...          datetime(year=2013, month=11, day=10),
    ...          datetime(year=2013, month=12, day=10),
    ...          datetime(year=2014, month=1, day=10),
    ...          datetime(year=2014, month=2, day=10)]

    >>> # Create ohlc
    >>> fig = create_candlestick(open_data, high_data,
    ...     low_data, close_data, dates=dates)
    >>> fig.show()

    """
    if dates is not None:
        utils.validate_equal_length(open, high, low, close, dates)
    else:
        utils.validate_equal_length(open, high, low, close)
    validate_ohlc(open, high, low, close, direction, **kwargs)

    if direction is "increasing":
        candle_incr_data = make_increasing_candle(open, high, low, close,
                                                  dates, **kwargs)
        data = candle_incr_data
    elif direction is "decreasing":
        candle_decr_data = make_decreasing_candle(open, high, low, close,
                                                  dates, **kwargs)
        data = candle_decr_data
    else:
        candle_incr_data = make_increasing_candle(open, high, low, close,
                                                  dates, **kwargs)
        candle_decr_data = make_decreasing_candle(open, high, low, close,
                                                  dates, **kwargs)
        data = candle_incr_data + candle_decr_data

    layout = graph_objs.Layout()
    return graph_objs.Figure(data=data, layout=layout)
Exemplo n.º 6
0
def get_subplots(rows=1, columns=1, print_grid=False, **kwargs):
    """Return a dictionary instance with the subplots set in 'layout'.

    Example 1:
    # stack two subplots vertically
    fig = tools.get_subplots(rows=2)
    fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], xaxis='x1', yaxis='y1')]
    fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], xaxis='x2', yaxis='y2')]

    Example 2:
    # print out string showing the subplot grid you've put in the layout
    fig = tools.get_subplots(rows=3, columns=2, print_grid=True)

    Keywords arguments with constant defaults:

    rows (kwarg, int greater than 0, default=1):
        Number of rows, evenly spaced vertically on the figure.

    columns (kwarg, int greater than 0, default=1):
        Number of columns, evenly spaced horizontally on the figure.

    horizontal_spacing (kwarg, float in [0,1], default=0.1):
        Space between subplot columns. Applied to all columns.

    vertical_spacing (kwarg, float in [0,1], default=0.05):
        Space between subplot rows. Applied to all rows.

    print_grid (kwarg, True | False, default=False):
        If True, prints a tab-delimited string representation
        of your plot grid.

    Keyword arguments with variable defaults:

    horizontal_spacing (kwarg, float in [0,1], default=0.2 / columns):
        Space between subplot columns.

    vertical_spacing (kwarg, float in [0,1], default=0.3 / rows):
        Space between subplot rows.

    """
    # TODO: protected until #282
    from plotly_study.graph_objs import graph_objs

    warnings.warn("tools.get_subplots is depreciated. "
                  "Please use tools.make_subplots instead.")

    # Throw exception for non-integer rows and columns
    if not isinstance(rows, int) or rows <= 0:
        raise Exception("Keyword argument 'rows' "
                        "must be an int greater than 0")
    if not isinstance(columns, int) or columns <= 0:
        raise Exception("Keyword argument 'columns' "
                        "must be an int greater than 0")

    # Throw exception if non-valid kwarg is sent
    VALID_KWARGS = ["horizontal_spacing", "vertical_spacing"]
    for key in kwargs.keys():
        if key not in VALID_KWARGS:
            raise Exception("Invalid keyword argument: '{0}'".format(key))

    # Set 'horizontal_spacing' / 'vertical_spacing' w.r.t. rows / columns
    try:
        horizontal_spacing = float(kwargs["horizontal_spacing"])
    except KeyError:
        horizontal_spacing = 0.2 / columns
    try:
        vertical_spacing = float(kwargs["vertical_spacing"])
    except KeyError:
        vertical_spacing = 0.3 / rows

    fig = dict(layout=graph_objs.Layout())  # will return this at the end
    plot_width = (1 - horizontal_spacing * (columns - 1)) / columns
    plot_height = (1 - vertical_spacing * (rows - 1)) / rows
    plot_num = 0
    for rrr in range(rows):
        for ccc in range(columns):
            xaxis_name = "xaxis{0}".format(plot_num + 1)
            x_anchor = "y{0}".format(plot_num + 1)
            x_start = (plot_width + horizontal_spacing) * ccc
            x_end = x_start + plot_width

            yaxis_name = "yaxis{0}".format(plot_num + 1)
            y_anchor = "x{0}".format(plot_num + 1)
            y_start = (plot_height + vertical_spacing) * rrr
            y_end = y_start + plot_height

            xaxis = dict(domain=[x_start, x_end], anchor=x_anchor)
            fig["layout"][xaxis_name] = xaxis
            yaxis = dict(domain=[y_start, y_end], anchor=y_anchor)
            fig["layout"][yaxis_name] = yaxis
            plot_num += 1

    if print_grid:
        print("This is the format of your plot grid!")
        grid_string = ""
        plot = 1
        for rrr in range(rows):
            grid_line = ""
            for ccc in range(columns):
                grid_line += "[{0}]\t".format(plot)
                plot += 1
            grid_string = grid_line + "\n" + grid_string
        print(grid_string)

    return graph_objs.Figure(fig)  # forces us to validate what we just did...
Exemplo n.º 7
0
def create_2d_density(
    x,
    y,
    colorscale="Earth",
    ncontours=20,
    hist_color=(0, 0, 0.5),
    point_color=(0, 0, 0.5),
    point_size=2,
    title="2D Density Plot",
    height=600,
    width=600,
):
    """
    Returns figure for a 2D density plot

    :param (list|array) x: x-axis data for plot generation
    :param (list|array) y: y-axis data for plot generation
    :param (str|tuple|list) colorscale: either a plotly scale name, an rgb
        or hex color, a color tuple or a list or tuple of colors. An rgb
        color is of the form 'rgb(x, y, z)' where x, y, z belong to the
        interval [0, 255] and a color tuple is a tuple of the form
        (a, b, c) where a, b and c belong to [0, 1]. If colormap is a
        list, it must contain the valid color types aforementioned as its
        members.
    :param (int) ncontours: the number of 2D contours to draw on the plot
    :param (str) hist_color: the color of the plotted histograms
    :param (str) point_color: the color of the scatter points
    :param (str) point_size: the color of the scatter points
    :param (str) title: set the title for the plot
    :param (float) height: the height of the chart
    :param (float) width: the width of the chart

    Examples
    --------

    Example 1: Simple 2D Density Plot

    >>> from plotly_study.figure_factory create_2d_density

    >>> import numpy as np

    >>> # Make data points
    >>> t = np.linspace(-1,1.2,2000)
    >>> x = (t**3)+(0.3*np.random.randn(2000))
    >>> y = (t**6)+(0.3*np.random.randn(2000))

    >>> # Create a figure
    >>> fig = create_2D_density(x, y)

    >>> # Plot the data
    >>> fig.show()

    Example 2: Using Parameters

    >>> from plotly_study.figure_factory create_2d_density

    >>> import numpy as np

    >>> # Make data points
    >>> t = np.linspace(-1,1.2,2000)
    >>> x = (t**3)+(0.3*np.random.randn(2000))
    >>> y = (t**6)+(0.3*np.random.randn(2000))

    >>> # Create custom colorscale
    >>> colorscale = ['#7A4579', '#D56073', 'rgb(236,158,105)',
    ...              (1, 1, 0.2), (0.98,0.98,0.98)]

    >>> # Create a figure
    >>> fig = create_2D_density(x, y, colorscale=colorscale,
    ...       hist_color='rgb(255, 237, 222)', point_size=3)

    >>> # Plot the data
    >>> fig.show()
    """

    # validate x and y are filled with numbers only
    for array in [x, y]:
        if not all(isinstance(element, Number) for element in array):
            raise plotly_study.exceptions.PlotlyError(
                "All elements of your 'x' and 'y' lists must be numbers.")

    # validate x and y are the same length
    if len(x) != len(y):
        raise plotly_study.exceptions.PlotlyError(
            "Both lists 'x' and 'y' must be the same length.")

    colorscale = clrs.validate_colors(colorscale, "rgb")
    colorscale = make_linear_colorscale(colorscale)

    # validate hist_color and point_color
    hist_color = clrs.validate_colors(hist_color, "rgb")
    point_color = clrs.validate_colors(point_color, "rgb")

    trace1 = graph_objs.Scatter(
        x=x,
        y=y,
        mode="markers",
        name="points",
        marker=dict(color=point_color[0], size=point_size, opacity=0.4),
    )
    trace2 = graph_objs.Histogram2dContour(
        x=x,
        y=y,
        name="density",
        ncontours=ncontours,
        colorscale=colorscale,
        reversescale=True,
        showscale=False,
    )
    trace3 = graph_objs.Histogram(x=x,
                                  name="x density",
                                  marker=dict(color=hist_color[0]),
                                  yaxis="y2")
    trace4 = graph_objs.Histogram(y=y,
                                  name="y density",
                                  marker=dict(color=hist_color[0]),
                                  xaxis="x2")
    data = [trace1, trace2, trace3, trace4]

    layout = graph_objs.Layout(
        showlegend=False,
        autosize=False,
        title=title,
        height=height,
        width=width,
        xaxis=dict(domain=[0, 0.85], showgrid=False, zeroline=False),
        yaxis=dict(domain=[0, 0.85], showgrid=False, zeroline=False),
        margin=dict(t=50),
        hovermode="closest",
        bargap=0,
        xaxis2=dict(domain=[0.85, 1], showgrid=False, zeroline=False),
        yaxis2=dict(domain=[0.85, 1], showgrid=False, zeroline=False),
    )

    fig = graph_objs.Figure(data=data, layout=layout)
    return fig
Exemplo n.º 8
0
def create_streamline(
    x, y, u, v, density=1, angle=math.pi / 9, arrow_scale=0.09, **kwargs
):
    """
    Returns data for a streamline plot.

    :param (list|ndarray) x: 1 dimensional, evenly spaced list or array
    :param (list|ndarray) y: 1 dimensional, evenly spaced list or array
    :param (ndarray) u: 2 dimensional array
    :param (ndarray) v: 2 dimensional array
    :param (float|int) density: controls the density of streamlines in
        plot. This is multiplied by 30 to scale similiarly to other
        available streamline functions such as matplotlib.
        Default = 1
    :param (angle in radians) angle: angle of arrowhead. Default = pi/9
    :param (float in [0,1]) arrow_scale: value to scale length of arrowhead
        Default = .09
    :param kwargs: kwargs passed through plotly_study.graph_objs.Scatter
        for more information on valid kwargs call
        help(plotly_study.graph_objs.Scatter)

    :rtype (dict): returns a representation of streamline figure.

    Example 1: Plot simple streamline and increase arrow size

    >>> from plotly_study.figure_factory import create_streamline
    >>> import numpy as np
    >>> import math

    >>> # Add data
    >>> x = np.linspace(-3, 3, 100)
    >>> y = np.linspace(-3, 3, 100)
    >>> Y, X = np.meshgrid(x, y)
    >>> u = -1 - X**2 + Y
    >>> v = 1 + X - Y**2
    >>> u = u.T  # Transpose
    >>> v = v.T  # Transpose

    >>> # Create streamline
    >>> fig = create_streamline(x, y, u, v, arrow_scale=.1)
    >>> fig.show()

    Example 2: from nbviewer.ipython.org/github/barbagroup/AeroPython

    >>> from plotly_study.figure_factory import create_streamline
    >>> import numpy as np
    >>> import math

    >>> # Add data
    >>> N = 50
    >>> x_start, x_end = -2.0, 2.0
    >>> y_start, y_end = -1.0, 1.0
    >>> x = np.linspace(x_start, x_end, N)
    >>> y = np.linspace(y_start, y_end, N)
    >>> X, Y = np.meshgrid(x, y)
    >>> ss = 5.0
    >>> x_s, y_s = -1.0, 0.0

    >>> # Compute the velocity field on the mesh grid
    >>> u_s = ss/(2*np.pi) * (X-x_s)/((X-x_s)**2 + (Y-y_s)**2)
    >>> v_s = ss/(2*np.pi) * (Y-y_s)/((X-x_s)**2 + (Y-y_s)**2)

    >>> # Create streamline
    >>> fig = create_streamline(x, y, u_s, v_s, density=2, name='streamline')

    >>> # Add source point
    >>> point = Scatter(x=[x_s], y=[y_s], mode='markers',
    ...                 marker=Marker(size=14), name='source point')

    >>> fig['data'].append(point)
    >>> fig.show()
    """
    utils.validate_equal_length(x, y)
    utils.validate_equal_length(u, v)
    validate_streamline(x, y)
    utils.validate_positive_scalars(density=density, arrow_scale=arrow_scale)

    streamline_x, streamline_y = _Streamline(
        x, y, u, v, density, angle, arrow_scale
    ).sum_streamlines()
    arrow_x, arrow_y = _Streamline(
        x, y, u, v, density, angle, arrow_scale
    ).get_streamline_arrows()

    streamline = graph_objs.Scatter(
        x=streamline_x + arrow_x, y=streamline_y + arrow_y, mode="lines", **kwargs
    )

    data = [streamline]
    layout = graph_objs.Layout(hovermode="closest")

    return graph_objs.Figure(data=data, layout=layout)
Exemplo n.º 9
0
def create_trisurf(
    x,
    y,
    z,
    simplices,
    colormap=None,
    show_colorbar=True,
    scale=None,
    color_func=None,
    title="Trisurf Plot",
    plot_edges=True,
    showbackground=True,
    backgroundcolor="rgb(230, 230, 230)",
    gridcolor="rgb(255, 255, 255)",
    zerolinecolor="rgb(255, 255, 255)",
    edges_color="rgb(50, 50, 50)",
    height=800,
    width=800,
    aspectratio=None,
):
    """
    Returns figure for a triangulated surface plot

    :param (array) x: data values of x in a 1D array
    :param (array) y: data values of y in a 1D array
    :param (array) z: data values of z in a 1D array
    :param (array) simplices: an array of shape (ntri, 3) where ntri is
        the number of triangles in the triangularization. Each row of the
        array contains the indicies of the verticies of each triangle
    :param (str|tuple|list) colormap: either a plotly scale name, an rgb
        or hex color, a color tuple or a list of colors. An rgb color is
        of the form 'rgb(x, y, z)' where x, y, z belong to the interval
        [0, 255] and a color tuple is a tuple of the form (a, b, c) where
        a, b and c belong to [0, 1]. If colormap is a list, it must
        contain the valid color types aforementioned as its members
    :param (bool) show_colorbar: determines if colorbar is visible
    :param (list|array) scale: sets the scale values to be used if a non-
        linearly interpolated colormap is desired. If left as None, a
        linear interpolation between the colors will be excecuted
    :param (function|list) color_func: The parameter that determines the
        coloring of the surface. Takes either a function with 3 arguments
        x, y, z or a list/array of color values the same length as
        simplices. If None, coloring will only depend on the z axis
    :param (str) title: title of the plot
    :param (bool) plot_edges: determines if the triangles on the trisurf
        are visible
    :param (bool) showbackground: makes background in plot visible
    :param (str) backgroundcolor: color of background. Takes a string of
        the form 'rgb(x,y,z)' x,y,z are between 0 and 255 inclusive
    :param (str) gridcolor: color of the gridlines besides the axes. Takes
        a string of the form 'rgb(x,y,z)' x,y,z are between 0 and 255
        inclusive
    :param (str) zerolinecolor: color of the axes. Takes a string of the
        form 'rgb(x,y,z)' x,y,z are between 0 and 255 inclusive
    :param (str) edges_color: color of the edges, if plot_edges is True
    :param (int|float) height: the height of the plot (in pixels)
    :param (int|float) width: the width of the plot (in pixels)
    :param (dict) aspectratio: a dictionary of the aspect ratio values for
        the x, y and z axes. 'x', 'y' and 'z' take (int|float) values

    Example 1: Sphere

    >>> # Necessary Imports for Trisurf
    >>> import numpy as np
    >>> from scipy.spatial import Delaunay

    >>> from plotly_study.figure_factory import create_trisurf
    >>> from plotly_study.graph_objs import graph_objs

    >>> # Make data for plot
    >>> u = np.linspace(0, 2*np.pi, 20)
    >>> v = np.linspace(0, np.pi, 20)
    >>> u,v = np.meshgrid(u,v)
    >>> u = u.flatten()
    >>> v = v.flatten()

    >>> x = np.sin(v)*np.cos(u)
    >>> y = np.sin(v)*np.sin(u)
    >>> z = np.cos(v)

    >>> points2D = np.vstack([u,v]).T
    >>> tri = Delaunay(points2D)
    >>> simplices = tri.simplices

    >>> # Create a figure
    >>> fig1 = create_trisurf(x=x, y=y, z=z, colormap="Rainbow",
    ...                       simplices=simplices)

    Example 2: Torus

    >>> # Necessary Imports for Trisurf
    >>> import numpy as np
    >>> from scipy.spatial import Delaunay

    >>> from plotly_study.figure_factory import create_trisurf
    >>> from plotly_study.graph_objs import graph_objs

    >>> # Make data for plot
    >>> u = np.linspace(0, 2*np.pi, 20)
    >>> v = np.linspace(0, 2*np.pi, 20)
    >>> u,v = np.meshgrid(u,v)
    >>> u = u.flatten()
    >>> v = v.flatten()

    >>> x = (3 + (np.cos(v)))*np.cos(u)
    >>> y = (3 + (np.cos(v)))*np.sin(u)
    >>> z = np.sin(v)

    >>> points2D = np.vstack([u,v]).T
    >>> tri = Delaunay(points2D)
    >>> simplices = tri.simplices

    >>> # Create a figure
    >>> fig1 = create_trisurf(x=x, y=y, z=z, colormap="Viridis",
    ...                       simplices=simplices)

    Example 3: Mobius Band

    >>> # Necessary Imports for Trisurf
    >>> import numpy as np
    >>> from scipy.spatial import Delaunay

    >>> from plotly_study.figure_factory import create_trisurf
    >>> from plotly_study.graph_objs import graph_objs

    >>> # Make data for plot
    >>> u = np.linspace(0, 2*np.pi, 24)
    >>> v = np.linspace(-1, 1, 8)
    >>> u,v = np.meshgrid(u,v)
    >>> u = u.flatten()
    >>> v = v.flatten()

    >>> tp = 1 + 0.5*v*np.cos(u/2.)
    >>> x = tp*np.cos(u)
    >>> y = tp*np.sin(u)
    >>> z = 0.5*v*np.sin(u/2.)

    >>> points2D = np.vstack([u,v]).T
    >>> tri = Delaunay(points2D)
    >>> simplices = tri.simplices

    >>> # Create a figure
    >>> fig1 = create_trisurf(x=x, y=y, z=z, colormap=[(0.2, 0.4, 0.6), (1, 1, 1)],
    ...                       simplices=simplices)

    Example 4: Using a Custom Colormap Function with Light Cone

    >>> # Necessary Imports for Trisurf
    >>> import numpy as np
    >>> from scipy.spatial import Delaunay

    >>> from plotly_study.figure_factory import create_trisurf
    >>> from plotly_study.graph_objs import graph_objs

    >>> # Make data for plot
    >>> u=np.linspace(-np.pi, np.pi, 30)
    >>> v=np.linspace(-np.pi, np.pi, 30)
    >>> u,v=np.meshgrid(u,v)
    >>> u=u.flatten()
    >>> v=v.flatten()

    >>> x = u
    >>> y = u*np.cos(v)
    >>> z = u*np.sin(v)

    >>> points2D = np.vstack([u,v]).T
    >>> tri = Delaunay(points2D)
    >>> simplices = tri.simplices

    >>> # Define distance function
    >>> def dist_origin(x, y, z):
    ...     return np.sqrt((1.0 * x)**2 + (1.0 * y)**2 + (1.0 * z)**2)

    >>> # Create a figure
    >>> fig1 = create_trisurf(x=x, y=y, z=z,
    ...                       colormap=['#FFFFFF', '#E4FFFE',
    ...                                 '#A4F6F9', '#FF99FE',
    ...                                 '#BA52ED'],
    ...                       scale=[0, 0.6, 0.71, 0.89, 1],
    ...                       simplices=simplices,
    ...                       color_func=dist_origin)

    Example 5: Enter color_func as a list of colors

    >>> # Necessary Imports for Trisurf
    >>> import numpy as np
    >>> from scipy.spatial import Delaunay
    >>> import random

    >>> from plotly_study.figure_factory import create_trisurf
    >>> from plotly_study.graph_objs import graph_objs

    >>> # Make data for plot
    >>> u=np.linspace(-np.pi, np.pi, 30)
    >>> v=np.linspace(-np.pi, np.pi, 30)
    >>> u,v=np.meshgrid(u,v)
    >>> u=u.flatten()
    >>> v=v.flatten()

    >>> x = u
    >>> y = u*np.cos(v)
    >>> z = u*np.sin(v)

    >>> points2D = np.vstack([u,v]).T
    >>> tri = Delaunay(points2D)
    >>> simplices = tri.simplices


    >>> colors = []
    >>> color_choices = ['rgb(0, 0, 0)', '#6c4774', '#d6c7dd']

    >>> for index in range(len(simplices)):
    >>>     colors.append(random.choice(color_choices))

    >>> fig = create_trisurf(
    ...     x, y, z, simplices,
    ...     color_func=colors,
    ...     show_colorbar=True,
    ...     edges_color='rgb(2, 85, 180)',
    ...     title=' Modern Art'
    ... )
    """
    if aspectratio is None:
        aspectratio = {"x": 1, "y": 1, "z": 1}

    # Validate colormap
    clrs.validate_colors(colormap)
    colormap, scale = clrs.convert_colors_to_same_type(
        colormap, colortype="tuple", return_default_colors=True, scale=scale
    )

    data1 = trisurf(
        x,
        y,
        z,
        simplices,
        show_colorbar=show_colorbar,
        color_func=color_func,
        colormap=colormap,
        scale=scale,
        edges_color=edges_color,
        plot_edges=plot_edges,
    )

    axis = dict(
        showbackground=showbackground,
        backgroundcolor=backgroundcolor,
        gridcolor=gridcolor,
        zerolinecolor=zerolinecolor,
    )
    layout = graph_objs.Layout(
        title=title,
        width=width,
        height=height,
        scene=graph_objs.layout.Scene(
            xaxis=graph_objs.layout.scene.XAxis(**axis),
            yaxis=graph_objs.layout.scene.YAxis(**axis),
            zaxis=graph_objs.layout.scene.ZAxis(**axis),
            aspectratio=dict(
                x=aspectratio["x"], y=aspectratio["y"], z=aspectratio["z"]
            ),
        ),
    )

    return graph_objs.Figure(data=data1, layout=layout)
Exemplo n.º 10
0
def create_quiver(x,
                  y,
                  u,
                  v,
                  scale=0.1,
                  arrow_scale=0.3,
                  angle=math.pi / 9,
                  scaleratio=None,
                  **kwargs):
    """
    Returns data for a quiver plot.

    :param (list|ndarray) x: x coordinates of the arrow locations
    :param (list|ndarray) y: y coordinates of the arrow locations
    :param (list|ndarray) u: x components of the arrow vectors
    :param (list|ndarray) v: y components of the arrow vectors
    :param (float in [0,1]) scale: scales size of the arrows(ideally to
        avoid overlap). Default = .1
    :param (float in [0,1]) arrow_scale: value multiplied to length of barb
        to get length of arrowhead. Default = .3
    :param (angle in radians) angle: angle of arrowhead. Default = pi/9
    :param (positive float) scaleratio: the ratio between the scale of the y-axis
        and the scale of the x-axis (scale_y / scale_x). Default = None, the
        scale ratio is not fixed.
    :param kwargs: kwargs passed through plotly_study.graph_objs.Scatter
        for more information on valid kwargs call
        help(plotly_study.graph_objs.Scatter)

    :rtype (dict): returns a representation of quiver figure.

    Example 1: Trivial Quiver

    >>> from plotly_study.figure_factory import create_quiver
    >>> import math

    >>> # 1 Arrow from (0,0) to (1,1)
    >>> fig = create_quiver(x=[0], y=[0], u=[1], v=[1], scale=1)
    >>> fig.show()


    Example 2: Quiver plot using meshgrid

    >>> from plotly_study.figure_factory import create_quiver

    >>> import numpy as np
    >>> import math

    >>> # Add data
    >>> x,y = np.meshgrid(np.arange(0, 2, .2), np.arange(0, 2, .2))
    >>> u = np.cos(x)*y
    >>> v = np.sin(x)*y

    >>> #Create quiver
    >>> fig = create_quiver(x, y, u, v)
    >>> fig.show()


    Example 3: Styling the quiver plot

    >>> from plotly_study.figure_factory import create_quiver
    >>> import numpy as np
    >>> import math

    >>> # Add data
    >>> x, y = np.meshgrid(np.arange(-np.pi, math.pi, .5),
    ...                    np.arange(-math.pi, math.pi, .5))
    >>> u = np.cos(x)*y
    >>> v = np.sin(x)*y

    >>> # Create quiver
    >>> fig = create_quiver(x, y, u, v, scale=.2, arrow_scale=.3, angle=math.pi/6,
    ...                     name='Wind Velocity', line=dict(width=1))

    >>> # Add title to layout
    >>> fig['layout'].update(title='Quiver Plot')
    >>> fig.show()


    Example 4: Forcing a fix scale ratio to maintain the arrow length

    >>> from plotly_study.figure_factory import create_quiver
    >>> import numpy as np

    >>> # Add data
    >>> x,y = np.meshgrid(np.arange(0.5, 3.5, .5), np.arange(0.5, 4.5, .5))
    >>> u = x
    >>> v = y
    >>> angle = np.arctan(v / u)
    >>> norm = 0.25
    >>> u = norm * np.cos(angle)
    >>> v = norm * np.sin(angle)

    >>> # Create quiver with a fix scale ratio
    >>> fig = create_quiver(x, y, u, v, scale = 1, scaleratio = 0.5)
    >>> fig.show()
    """
    utils.validate_equal_length(x, y, u, v)
    utils.validate_positive_scalars(arrow_scale=arrow_scale, scale=scale)

    if scaleratio is None:
        quiver_obj = _Quiver(x, y, u, v, scale, arrow_scale, angle)
    else:
        quiver_obj = _Quiver(x, y, u, v, scale, arrow_scale, angle, scaleratio)

    barb_x, barb_y = quiver_obj.get_barbs()
    arrow_x, arrow_y = quiver_obj.get_quiver_arrows()

    quiver_plot = graph_objs.Scatter(x=barb_x + arrow_x,
                                     y=barb_y + arrow_y,
                                     mode="lines",
                                     **kwargs)

    data = [quiver_plot]

    if scaleratio is None:
        layout = graph_objs.Layout(hovermode="closest")
    else:
        layout = graph_objs.Layout(hovermode="closest",
                                   yaxis=dict(scaleratio=scaleratio,
                                              scaleanchor="x"))

    return graph_objs.Figure(data=data, layout=layout)
Exemplo n.º 11
0
def create_distplot(
    hist_data,
    group_labels,
    bin_size=1.0,
    curve_type="kde",
    colors=None,
    rug_text=None,
    histnorm=DEFAULT_HISTNORM,
    show_hist=True,
    show_curve=True,
    show_rug=True,
):
    """
    BETA function that creates a distplot similar to seaborn.distplot

    The distplot can be composed of all or any combination of the following
    3 components: (1) histogram, (2) curve: (a) kernel density estimation
    or (b) normal curve, and (3) rug plot. Additionally, multiple distplots
    (from multiple datasets) can be created in the same plot.

    :param (list[list]) hist_data: Use list of lists to plot multiple data
        sets on the same plot.
    :param (list[str]) group_labels: Names for each data set.
    :param (list[float]|float) bin_size: Size of histogram bins.
        Default = 1.
    :param (str) curve_type: 'kde' or 'normal'. Default = 'kde'
    :param (str) histnorm: 'probability density' or 'probability'
        Default = 'probability density'
    :param (bool) show_hist: Add histogram to distplot? Default = True
    :param (bool) show_curve: Add curve to distplot? Default = True
    :param (bool) show_rug: Add rug to distplot? Default = True
    :param (list[str]) colors: Colors for traces.
    :param (list[list]) rug_text: Hovertext values for rug_plot,
    :return (dict): Representation of a distplot figure.

    Example 1: Simple distplot of 1 data set

    >>> from plotly_study.figure_factory import create_distplot

    >>> hist_data = [[1.1, 1.1, 2.5, 3.0, 3.5,
    ...               3.5, 4.1, 4.4, 4.5, 4.5,
    ...               5.0, 5.0, 5.2, 5.5, 5.5,
    ...               5.5, 5.5, 5.5, 6.1, 7.0]]
    >>> group_labels = ['distplot example']
    >>> fig = create_distplot(hist_data, group_labels)
    >>> fig.show()


    Example 2: Two data sets and added rug text
    
    >>> from plotly_study.figure_factory import create_distplot
    >>> # Add histogram data
    >>> hist1_x = [0.8, 1.2, 0.2, 0.6, 1.6,
    ...            -0.9, -0.07, 1.95, 0.9, -0.2,
    ...            -0.5, 0.3, 0.4, -0.37, 0.6]
    >>> hist2_x = [0.8, 1.5, 1.5, 0.6, 0.59,
    ...            1.0, 0.8, 1.7, 0.5, 0.8,
    ...            -0.3, 1.2, 0.56, 0.3, 2.2]

    >>> # Group data together
    >>> hist_data = [hist1_x, hist2_x]

    >>> group_labels = ['2012', '2013']

    >>> # Add text
    >>> rug_text_1 = ['a1', 'b1', 'c1', 'd1', 'e1',
    ...       'f1', 'g1', 'h1', 'i1', 'j1',
    ...       'k1', 'l1', 'm1', 'n1', 'o1']

    >>> rug_text_2 = ['a2', 'b2', 'c2', 'd2', 'e2',
    ...       'f2', 'g2', 'h2', 'i2', 'j2',
    ...       'k2', 'l2', 'm2', 'n2', 'o2']

    >>> # Group text together
    >>> rug_text_all = [rug_text_1, rug_text_2]

    >>> # Create distplot
    >>> fig = create_distplot(
    ...     hist_data, group_labels, rug_text=rug_text_all, bin_size=.2)

    >>> # Add title
    >>> fig['layout'].update(title='Dist Plot')
    >>> fig.show()


    Example 3: Plot with normal curve and hide rug plot
    
    >>> from plotly_study.figure_factory import create_distplot
    >>> import numpy as np

    >>> x1 = np.random.randn(190)
    >>> x2 = np.random.randn(200)+1
    >>> x3 = np.random.randn(200)-1
    >>> x4 = np.random.randn(210)+2

    >>> hist_data = [x1, x2, x3, x4]
    >>> group_labels = ['2012', '2013', '2014', '2015']

    >>> fig = create_distplot(
    ...     hist_data, group_labels, curve_type='normal',
    ...     show_rug=False, bin_size=.4)


    Example 4: Distplot with Pandas
    
    >>> from plotly_study.figure_factory import create_distplot
    >>> import numpy as np
    >>> import pandas as pd

    >>> df = pd.DataFrame({'2012': np.random.randn(200),
    >>>                    '2013': np.random.randn(200)+1})
    >>> fig = create_distplot([df[c] for c in df.columns], df.columns)
    >>> fig.show()
    """
    if colors is None:
        colors = []
    if rug_text is None:
        rug_text = []

    validate_distplot(hist_data, curve_type)
    utils.validate_equal_length(hist_data, group_labels)

    if isinstance(bin_size, (float, int)):
        bin_size = [bin_size] * len(hist_data)

    hist = _Distplot(
        hist_data,
        histnorm,
        group_labels,
        bin_size,
        curve_type,
        colors,
        rug_text,
        show_hist,
        show_curve,
    ).make_hist()

    if curve_type == "normal":
        curve = _Distplot(
            hist_data,
            histnorm,
            group_labels,
            bin_size,
            curve_type,
            colors,
            rug_text,
            show_hist,
            show_curve,
        ).make_normal()
    else:
        curve = _Distplot(
            hist_data,
            histnorm,
            group_labels,
            bin_size,
            curve_type,
            colors,
            rug_text,
            show_hist,
            show_curve,
        ).make_kde()

    rug = _Distplot(
        hist_data,
        histnorm,
        group_labels,
        bin_size,
        curve_type,
        colors,
        rug_text,
        show_hist,
        show_curve,
    ).make_rug()

    data = []
    if show_hist:
        data.append(hist)
    if show_curve:
        data.append(curve)
    if show_rug:
        data.append(rug)
        layout = graph_objs.Layout(
            barmode="overlay",
            hovermode="closest",
            legend=dict(traceorder="reversed"),
            xaxis1=dict(domain=[0.0, 1.0], anchor="y2", zeroline=False),
            yaxis1=dict(domain=[0.35, 1], anchor="free", position=0.0),
            yaxis2=dict(domain=[0, 0.25],
                        anchor="x1",
                        dtick=1,
                        showticklabels=False),
        )
    else:
        layout = graph_objs.Layout(
            barmode="overlay",
            hovermode="closest",
            legend=dict(traceorder="reversed"),
            xaxis1=dict(domain=[0.0, 1.0], anchor="y2", zeroline=False),
            yaxis1=dict(domain=[0.0, 1], anchor="free", position=0.0),
        )

    data = sum(data, [])
    return graph_objs.Figure(data=data, layout=layout)