Пример #1
0
    def test_default_dendrogram(self):
        X = np.array([[1, 2, 3, 4], [1, 1, 3, 4], [1, 2, 1, 4], [1, 2, 3, 1]])
        dendro = tls.FigureFactory.create_dendrogram(X=X)

        expected_dendro = go.Figure(
            data=go.Data([
                go.Scatter(x=np.array([25., 25., 35., 35.]),
                           y=np.array([0., 1., 1., 0.]),
                           marker=go.Marker(color='rgb(61,153,112)'),
                           mode='lines',
                           xaxis='x',
                           yaxis='y'),
                go.Scatter(x=np.array([15., 15., 30., 30.]),
                           y=np.array([0., 2.23606798, 2.23606798, 1.]),
                           marker=go.Marker(color='rgb(61,153,112)'),
                           mode='lines',
                           xaxis='x',
                           yaxis='y'),
                go.Scatter(x=np.array([5., 5., 22.5, 22.5]),
                           y=np.array([0., 3.60555128, 3.60555128,
                                       2.23606798]),
                           marker=go.Marker(color='rgb(0,116,217)'),
                           mode='lines',
                           xaxis='x',
                           yaxis='y')
            ]),
            layout=go.Layout(autosize=False,
                             height='100%',
                             hovermode='closest',
                             showlegend=False,
                             width='100%',
                             xaxis=go.XAxis(mirror='allticks',
                                            rangemode='tozero',
                                            showgrid=False,
                                            showline=True,
                                            showticklabels=True,
                                            tickmode='array',
                                            ticks='outside',
                                            ticktext=np.array(
                                                ['3', '2', '0', '1']),
                                            tickvals=[5.0, 15.0, 25.0, 35.0],
                                            type='linear',
                                            zeroline=False),
                             yaxis=go.YAxis(mirror='allticks',
                                            rangemode='tozero',
                                            showgrid=False,
                                            showline=True,
                                            showticklabels=True,
                                            ticks='outside',
                                            type='linear',
                                            zeroline=False)))

        self.assertEqual(len(dendro['data']), 3)

        # this is actually a bit clearer when debugging tests.
        self.assert_dict_equal(dendro['data'][0], expected_dendro['data'][0])
        self.assert_dict_equal(dendro['data'][1], expected_dendro['data'][1])
        self.assert_dict_equal(dendro['data'][2], expected_dendro['data'][2])

        self.assert_dict_equal(dendro['layout'], expected_dendro['layout'])
Пример #2
0
def scatterplot(dataframe, headers, diag, size, height, width, title,
                **kwargs):
    """
    Refer to FigureFactory.create_scatterplotmatrix() for docstring

    Returns fig for scatterplotmatrix without index

    """
    dim = len(dataframe)
    fig = make_subplots(rows=dim, cols=dim, print_grid=False)
    trace_list = []
    # Insert traces into trace_list
    for listy in dataframe:
        for listx in dataframe:
            if (listx == listy) and (diag == "histogram"):
                trace = graph_objs.Histogram(x=listx, showlegend=False)
            elif (listx == listy) and (diag == "box"):
                trace = graph_objs.Box(y=listx, name=None, showlegend=False)
            else:
                if "marker" in kwargs:
                    kwargs["marker"]["size"] = size
                    trace = graph_objs.Scatter(x=listx,
                                               y=listy,
                                               mode="markers",
                                               showlegend=False,
                                               **kwargs)
                    trace_list.append(trace)
                else:
                    trace = graph_objs.Scatter(x=listx,
                                               y=listy,
                                               mode="markers",
                                               marker=dict(size=size),
                                               showlegend=False,
                                               **kwargs)
            trace_list.append(trace)

    trace_index = 0
    indices = range(1, dim + 1)
    for y_index in indices:
        for x_index in indices:
            fig.append_trace(trace_list[trace_index], y_index, x_index)
            trace_index += 1

    # Insert headers into the figure
    for j in range(dim):
        xaxis_key = "xaxis{}".format((dim * dim) - dim + 1 + j)
        fig["layout"][xaxis_key].update(title=headers[j])
    for j in range(dim):
        yaxis_key = "yaxis{}".format(1 + (dim * j))
        fig["layout"][yaxis_key].update(title=headers[j])

    fig["layout"].update(height=height,
                         width=width,
                         title=title,
                         showlegend=True)

    hide_tick_labels_from_box_subplots(fig)

    return fig
Пример #3
0
def make_non_outlier_interval(d1, d2):
    """
    Returns the scatterplot fig of most of a violin plot.
    """
    return graph_objs.Scatter(x=[0, 0],
                              y=[d1, d2],
                              name='',
                              mode='lines',
                              line=graph_objs.Line(width=1.5,
                                                   color='rgb(0,0,0)'))
Пример #4
0
def make_median(q2):
    """
    Formats the 'median' hovertext for a violin plot.
    """
    return graph_objs.Scatter(x=[0],
                              y=[q2],
                              text=['median: ' + '{:0.2f}'.format(q2)],
                              mode='markers',
                              marker=dict(symbol='square',
                                          color='rgb(255,255,255)'),
                              hoverinfo='text')
Пример #5
0
def make_delta(m1, m2):
    """
    Formats the 'delta of medians' hovertext for a violin plot.
    """
    return graph_objs.Scatter(
        x=[0],
        y=[(m1 + m2) / 2.0],
        text=['delta: ' + '{:0.2f}'.format(abs(m1 - m2))],
        mode='markers',
        marker=dict(symbol='square', color='rgb(255,255,255)'),
        hoverinfo='text')
Пример #6
0
def make_violin_rugplot(vals, pdf_max, distance, color='#1f77b4'):
    """
    Returns a rugplot fig for a violin plot.
    """
    return graph_objs.Scatter(y=vals,
                              x=[-pdf_max - distance] * len(vals),
                              marker=graph_objs.Marker(color=color,
                                                       symbol='line-ew-open'),
                              mode='markers',
                              name='',
                              showlegend=False,
                              hoverinfo='y')
Пример #7
0
def make_median(q2):
    """
    Formats the 'median' hovertext for a violin plot.
    """
    return graph_objs.Scatter(
        x=[0],
        y=[q2],
        text=["median: " + "{:0.2f}".format(q2)],
        mode="markers",
        marker=dict(symbol="square", color="rgb(255,255,255)"),
        hoverinfo="text",
    )
Пример #8
0
def make_violin_rugplot(vals, pdf_max, distance, color="#1f77b4"):
    """
    Returns a rugplot fig for a violin plot.
    """
    return graph_objs.Scatter(
        y=vals,
        x=[-pdf_max - distance] * len(vals),
        marker=graph_objs.scatter.Marker(color=color, symbol="line-ew-open"),
        mode="markers",
        name="",
        showlegend=False,
        hoverinfo="y",
    )
Пример #9
0
def make_diff(m1, m2):
    """
    Makes the difference of medians for a violin plot.
    """
    return graph_objs.Scatter(x=[0, 0],
                              y=[m1, m2],
                              text=[
                                  'median 1: ' + '{:0.2f}'.format(m1),
                                  'median 2: ' + '{:0.2f}'.format(m2)
                              ],
                              mode='lines',
                              line=graph_objs.Line(width=2,
                                                   color='rgb(0,0,0)'),
                              hoverinfo='text')
Пример #10
0
def make_quartiles(q1, q3):
    """
    Makes the upper and lower quartiles for a violin plot.
    """
    return graph_objs.Scatter(x=[0, 0],
                              y=[q1, q3],
                              text=[
                                  'lower-quartile: ' + '{:0.2f}'.format(q1),
                                  'upper-quartile: ' + '{:0.2f}'.format(q3)
                              ],
                              mode='lines',
                              line=graph_objs.Line(width=4,
                                                   color='rgb(0,0,0)'),
                              hoverinfo='text')
Пример #11
0
def make_quartiles(q1, q3):
    """
    Makes the upper and lower quartiles for a violin plot.
    """
    return graph_objs.Scatter(
        x=[0, 0],
        y=[q1, q3],
        text=[
            "lower-quartile: " + "{:0.2f}".format(q1),
            "upper-quartile: " + "{:0.2f}".format(q3),
        ],
        mode="lines",
        line=graph_objs.scatter.Line(width=4, color="rgb(0,0,0)"),
        hoverinfo="text",
    )
Пример #12
0
def build_arrows(x, y, u, v, scale, arrow_scale, angle, scaleratio, **kwargs):

    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)

    return [quiver_plot]
Пример #13
0
def make_half_violin(x, y, fillcolor='#1f77b4', linecolor='rgb(0, 0, 0)'):
    """
    Produces a sideways probability distribution fig violin plot.
    """
    text = ['(pdf(y), y)=(' + '{:0.2f}'.format(x[i]) +
            ', ' + '{:0.2f}'.format(y[i]) + ')'
            for i in range(len(x))]

    return graph_objs.Scatter(
        x=x,
        y=y,
        mode='lines',
        name='',
        text=text,
        fill='tonextx',
        fillcolor=fillcolor,
        line=graph_objs.Line(width=0.5, color=linecolor, shape='spline'),
        hoverinfo='text',
        opacity=0.5
    )
Пример #14
0
def make_half_violin(x, y, fillcolor="#1f77b4", linecolor="rgb(0, 0, 0)"):
    """
    Produces a sideways probability distribution fig violin plot.
    """
    text = [
        "(pdf(y), y)=(" + "{:0.2f}".format(x[i]) + ", " + "{:0.2f}".format(y[i]) + ")"
        for i in range(len(x))
    ]

    return graph_objs.Scatter(
        x=x,
        y=y,
        mode="lines",
        name="",
        text=text,
        fill="tonextx",
        fillcolor=fillcolor,
        line=graph_objs.scatter.Line(width=0.5, color=linecolor, shape="spline"),
        hoverinfo="text",
        opacity=0.5,
    )
def update_graph(xaxis_name, yaxis_name):

    trace = go.Scatter(x=xaxis_name,
                       y=yaxis_name,
                       text=df['name'],
                       mode='markers',
                       markers={
                           'size': 15,
                           'opacity': 0.5,
                           'line': {
                               'width': 0.5,
                               'color': 'white'
                           }
                       })
    layout = go.Layout(
        title='Carros',
        xaxis={'title': xaxis_name},
        yaxis={'tilte': yaxis_name},
    )

    return {'data': [trace], 'layout': layout}
Пример #16
0
    def get_dendrogram_traces(self, X, colorscale):
        from plotly.graph_objs import graph_objs

        Z = sch.linkage(X, method=self.method, metric=self.metric)
        P = sch.dendrogram(Z,
                           orientation=self.orientation,
                           labels=self.labels,
                           no_plot=True)

        icoord = scp.array(P['icoord'])
        dcoord = scp.array(P['dcoord'])
        ordered_labels = scp.array(P['ivl'])
        color_list = scp.array(P['color_list'])
        colors = self.get_color_dict(colorscale)

        trace_list = []

        def trace_axis(axis):
            try:
                return axis[0] + str(int(axis[-1]))
            except:
                return axis[0]

        for xs, ys, color_key in zip(icoord, dcoord, color_list):
            if self.orientation not in ['top', 'bottom']:
                xs, ys = ys, xs

            trace = graph_objs.Scatter(
                x=xs * self.sign[self.xaxis],
                y=ys * self.sign[self.yaxis],
                mode='lines',
                xaxis=trace_axis(self.xaxis),
                yaxis=trace_axis(self.yaxis),
                marker=graph_objs.Marker(color=colors[color_key]),
            )

            trace_list.append(trace)

        return trace_list, icoord, dcoord, ordered_labels, P['leaves']
Пример #17
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,
):
    """
    **deprecated**, use instead
    :func:`plotly.express.density_heatmap`.

    :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.figure_factory import 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.figure_factory import 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.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.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
Пример #18
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
Пример #19
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.graph_objs.Scatter
        for more information on valid kwargs call
        help(plotly.graph_objs.Scatter)

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

    Example 1: Trivial Quiver
    ```
    import plotly.plotly as py
    from plotly.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)

    py.plot(fig, filename='quiver')
    ```

    Example 2: Quiver plot using meshgrid
    ```
    import plotly.plotly as py
    from plotly.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)

    # Plot
    py.plot(fig, filename='quiver')
    ```

    Example 3: Styling the quiver plot
    ```
    import plotly.plotly as py
    from plotly.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')

    # Plot
    py.plot(fig, filename='quiver')
    ```

    Example 4: Forcing a fix scale ratio to maintain the arrow length
    ```
    import plotly.plotly as py
    from plotly.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)

    # Plot
    py.plot(fig, filename='quiver')
    ```
    """
    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)
Пример #20
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

    Example 1: Simple 2D Density Plot
    ```
    import plotly.plotly as py
    from plotly.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
    py.iplot(fig, filename='simple-2d-density')
    ```

    Example 2: Using Parameters
    ```
    import plotly.plotly as py
    from plotly.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
    py.iplot(fig, filename='use-parameters')
    ```
    """

    # 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 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 exceptions.PlotlyError(
            "Both lists 'x' and 'y' must be the same length."
        )

    colorscale = utils.validate_colors(colorscale, 'rgb')
    colorscale = make_linear_colorscale(colorscale)

    # validate hist_color and point_color
    hist_color = utils.validate_colors(hist_color, 'rgb')
    point_color = utils.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
Пример #21
0
def _facet_grid(df, x, y, facet_row, facet_col, num_of_rows, num_of_cols,
                facet_row_labels, facet_col_labels, trace_type, flipped_rows,
                flipped_cols, show_boxes, marker_color, kwargs_trace,
                kwargs_marker):

    fig = make_subplots(rows=num_of_rows,
                        cols=num_of_cols,
                        shared_xaxes=True,
                        shared_yaxes=True,
                        horizontal_spacing=SUBPLOT_SPACING,
                        vertical_spacing=SUBPLOT_SPACING,
                        print_grid=False)
    annotations = []
    if not facet_row and not facet_col:
        trace = graph_objs.Scatter(x=df[x],
                                   y=df[y],
                                   mode='markers',
                                   type=trace_type,
                                   marker=dict(color=marker_color,
                                               **kwargs_marker),
                                   **kwargs_trace)
        fig.append_trace(trace, 1, 1)

    elif (facet_row and not facet_col) or (not facet_row and facet_col):
        groups_by_facet = list(
            df.groupby(facet_row if facet_row else facet_col))
        for j, group in enumerate(groups_by_facet):
            trace = graph_objs.Scatter(x=group[1][x],
                                       y=group[1][y],
                                       mode='markers',
                                       type=trace_type,
                                       marker=dict(color=marker_color,
                                                   **kwargs_marker),
                                       **kwargs_trace)
            fig.append_trace(trace, j + 1 if facet_row else 1,
                             1 if facet_row else j + 1)

            label = _return_label(
                group[0], facet_row_labels if facet_row else facet_col_labels,
                facet_row if facet_row else facet_col)

            annotations.append(
                _annotation_dict(label,
                                 num_of_rows - j if facet_row else j + 1,
                                 num_of_rows if facet_row else num_of_cols,
                                 'row' if facet_row else 'col', flipped_rows))

    elif facet_row and facet_col:
        groups_by_facets = list(df.groupby([facet_row, facet_col]))
        tuple_to_facet_group = {item[0]: item[1] for item in groups_by_facets}

        row_values = df[facet_row].unique()
        col_values = df[facet_col].unique()
        for row_count, x_val in enumerate(row_values):
            for col_count, y_val in enumerate(col_values):
                try:
                    group = tuple_to_facet_group[(x_val, y_val)]
                except KeyError:
                    group = pd.DataFrame([[None, None]], columns=[x, y])
                trace = graph_objs.Scatter(x=group[x],
                                           y=group[y],
                                           mode='markers',
                                           type=trace_type,
                                           marker=dict(color=marker_color,
                                                       **kwargs_marker),
                                           **kwargs_trace)
                fig.append_trace(trace, row_count + 1, col_count + 1)
                if row_count == 0:
                    label = _return_label(col_values[col_count],
                                          facet_col_labels, facet_col)
                    annotations.append(
                        _annotation_dict(label,
                                         col_count + 1,
                                         num_of_cols,
                                         row_col='col',
                                         flipped=flipped_cols))

            label = _return_label(row_values[row_count], facet_row_labels,
                                  facet_row)
            annotations.append(
                _annotation_dict(label,
                                 num_of_rows - row_count,
                                 num_of_rows,
                                 row_col='row',
                                 flipped=flipped_rows))

    # add annotations
    fig['layout']['annotations'] = annotations

    return fig
Пример #22
0
    def test_dendrogram_random_matrix(self):

        # create a random uncorrelated matrix
        X = np.random.rand(5, 5)

        # variable 2 is correlated with all the other variables
        X[2, :] = sum(X, 0)

        names = ['Jack', 'Oxana', 'John', 'Chelsea', 'Mark']
        dendro = tls.FigureFactory.create_dendrogram(X, labels=names)

        expected_dendro = go.Figure(
            data=go.Data([
                go.Scatter(marker=go.Marker(color='rgb(61,153,112)'),
                           mode='lines',
                           xaxis='x',
                           yaxis='y'),
                go.Scatter(marker=go.Marker(color='rgb(61,153,112)'),
                           mode='lines',
                           xaxis='x',
                           yaxis='y'),
                go.Scatter(marker=go.Marker(color='rgb(61,153,112)'),
                           mode='lines',
                           xaxis='x',
                           yaxis='y'),
                go.Scatter(marker=go.Marker(color='rgb(0,116,217)'),
                           mode='lines',
                           xaxis='x',
                           yaxis='y')
            ]),
            layout=go.Layout(autosize=False,
                             height='100%',
                             hovermode='closest',
                             showlegend=False,
                             width='100%',
                             xaxis=go.XAxis(
                                 mirror='allticks',
                                 rangemode='tozero',
                                 showgrid=False,
                                 showline=True,
                                 showticklabels=True,
                                 tickmode='array',
                                 ticks='outside',
                                 tickvals=[5.0, 15.0, 25.0, 35.0, 45.0],
                                 type='linear',
                                 zeroline=False),
                             yaxis=go.YAxis(mirror='allticks',
                                            rangemode='tozero',
                                            showgrid=False,
                                            showline=True,
                                            showticklabels=True,
                                            ticks='outside',
                                            type='linear',
                                            zeroline=False)))

        self.assertEqual(len(dendro['data']), 4)

        # it's random, so we can only check that the values aren't equal
        y_vals = [
            dendro['data'][0].pop('y'), dendro['data'][1].pop('y'),
            dendro['data'][2].pop('y'), dendro['data'][3].pop('y')
        ]
        for i in range(len(y_vals)):
            for j in range(len(y_vals)):
                if i != j:
                    self.assertFalse(np.allclose(y_vals[i], y_vals[j]))

        x_vals = [
            dendro['data'][0].pop('x'), dendro['data'][1].pop('x'),
            dendro['data'][2].pop('x'), dendro['data'][3].pop('x')
        ]
        for i in range(len(x_vals)):
            for j in range(len(x_vals)):
                if i != j:
                    self.assertFalse(np.allclose(x_vals[i], x_vals[j]))

        # we also need to check the ticktext manually
        xaxis_ticktext = dendro['layout']['xaxis'].pop('ticktext')
        self.assertEqual(xaxis_ticktext[0], 'John')

        # this is actually a bit clearer when debugging tests.
        self.assert_dict_equal(dendro['data'][0], expected_dendro['data'][0])
        self.assert_dict_equal(dendro['data'][1], expected_dendro['data'][1])
        self.assert_dict_equal(dendro['data'][2], expected_dendro['data'][2])
        self.assert_dict_equal(dendro['data'][3], expected_dendro['data'][3])

        self.assert_dict_equal(dendro['layout'], expected_dendro['layout'])
Пример #23
0
    def test_dendrogram_colorscale(self):
        X = np.array([[1, 2, 3, 4], [1, 1, 3, 4], [1, 2, 1, 4], [1, 2, 3, 1]])
        greyscale = [
            'rgb(0,0,0)',  # black
            'rgb(05,105,105)',  # dim grey
            'rgb(128,128,128)',  # grey
            'rgb(169,169,169)',  # dark grey
            'rgb(192,192,192)',  # silver
            'rgb(211,211,211)',  # light grey
            'rgb(220,220,220)',  # gainsboro
            'rgb(245,245,245)'
        ]  # white smoke

        dendro = tls.FigureFactory.create_dendrogram(X, colorscale=greyscale)

        expected_dendro = go.Figure(
            data=go.Data([
                go.Scatter(x=np.array([25., 25., 35., 35.]),
                           y=np.array([0., 1., 1., 0.]),
                           marker=go.Marker(color='rgb(128,128,128)'),
                           mode='lines',
                           xaxis='x',
                           yaxis='y'),
                go.Scatter(x=np.array([15., 15., 30., 30.]),
                           y=np.array([0., 2.23606798, 2.23606798, 1.]),
                           marker=go.Marker(color='rgb(128,128,128)'),
                           mode='lines',
                           xaxis='x',
                           yaxis='y'),
                go.Scatter(x=np.array([5., 5., 22.5, 22.5]),
                           y=np.array([0., 3.60555128, 3.60555128,
                                       2.23606798]),
                           marker=go.Marker(color='rgb(0,0,0)'),
                           mode='lines',
                           xaxis='x',
                           yaxis='y')
            ]),
            layout=go.Layout(autosize=False,
                             height='100%',
                             hovermode='closest',
                             showlegend=False,
                             width='100%',
                             xaxis=go.XAxis(mirror='allticks',
                                            rangemode='tozero',
                                            showgrid=False,
                                            showline=True,
                                            showticklabels=True,
                                            tickmode='array',
                                            ticks='outside',
                                            ticktext=np.array(
                                                ['3', '2', '0', '1']),
                                            tickvals=[5.0, 15.0, 25.0, 35.0],
                                            type='linear',
                                            zeroline=False),
                             yaxis=go.YAxis(mirror='allticks',
                                            rangemode='tozero',
                                            showgrid=False,
                                            showline=True,
                                            showticklabels=True,
                                            ticks='outside',
                                            type='linear',
                                            zeroline=False)))

        self.assertEqual(len(dendro['data']), 3)

        # this is actually a bit clearer when debugging tests.
        self.assert_dict_equal(dendro['data'][0], expected_dendro['data'][0])
        self.assert_dict_equal(dendro['data'][1], expected_dendro['data'][1])
        self.assert_dict_equal(dendro['data'][2], expected_dendro['data'][2])
Пример #24
0
def scatterplot_dict(dataframe, headers, diag, size,
                      height, width, title, index, index_vals,
                      endpts, colormap, colormap_type, **kwargs):
    """
    Refer to FigureFactory.create_scatterplotmatrix() for docstring

    Returns fig for scatterplotmatrix with both index and colormap picked.
    Used if colormap is a dictionary with index values as keys pointing to
    colors. Forces colormap_type to behave categorically because it would
    not make sense colors are assigned to each index value and thus
    implies that a categorical approach should be taken

    """

    theme = colormap
    dim = len(dataframe)
    fig = make_subplots(rows=dim, cols=dim, print_grid=False)
    trace_list = []
    legend_param = 0
    # Work over all permutations of list pairs
    for listy in dataframe:
        for listx in dataframe:
            # create a dictionary for index_vals
            unique_index_vals = {}
            for name in index_vals:
                if name not in unique_index_vals:
                    unique_index_vals[name] = []

            # Fill all the rest of the names into the dictionary
            for name in sorted(unique_index_vals.keys()):
                new_listx = []
                new_listy = []
                for j in range(len(index_vals)):
                    if index_vals[j] == name:
                        new_listx.append(listx[j])
                        new_listy.append(listy[j])
                # Generate trace with VISIBLE icon
                if legend_param == 1:
                    if (listx == listy) and (diag == 'histogram'):
                        trace = graph_objs.Histogram(
                            x=new_listx,
                            marker=dict(
                                color=theme[name]),
                            showlegend=True
                        )
                    elif (listx == listy) and (diag == 'box'):
                        trace = graph_objs.Box(
                            y=new_listx,
                            name=None,
                            marker=dict(
                                color=theme[name]),
                            showlegend=True
                        )
                    else:
                        if 'marker' in kwargs:
                            kwargs['marker']['size'] = size
                            kwargs['marker']['color'] = theme[name]
                            trace = graph_objs.Scatter(
                                x=new_listx,
                                y=new_listy,
                                mode='markers',
                                name=name,
                                showlegend=True,
                                **kwargs
                            )
                        else:
                            trace = graph_objs.Scatter(
                                x=new_listx,
                                y=new_listy,
                                mode='markers',
                                name=name,
                                marker=dict(
                                    size=size,
                                    color=theme[name]),
                                showlegend=True,
                                **kwargs
                            )
                # Generate trace with INVISIBLE icon
                else:
                    if (listx == listy) and (diag == 'histogram'):
                        trace = graph_objs.Histogram(
                            x=new_listx,
                            marker=dict(
                                color=theme[name]),
                            showlegend=False
                        )
                    elif (listx == listy) and (diag == 'box'):
                        trace = graph_objs.Box(
                            y=new_listx,
                            name=None,
                            marker=dict(
                                color=theme[name]),
                            showlegend=False
                        )
                    else:
                        if 'marker' in kwargs:
                            kwargs['marker']['size'] = size
                            kwargs['marker']['color'] = theme[name]
                            trace = graph_objs.Scatter(
                                x=new_listx,
                                y=new_listy,
                                mode='markers',
                                name=name,
                                showlegend=False,
                                **kwargs
                            )
                        else:
                            trace = graph_objs.Scatter(
                                x=new_listx,
                                y=new_listy,
                                mode='markers',
                                name=name,
                                marker=dict(
                                    size=size,
                                    color=theme[name]),
                                showlegend=False,
                                **kwargs
                            )
                # Push the trace into dictionary
                unique_index_vals[name] = trace
            trace_list.append(unique_index_vals)
            legend_param += 1

    trace_index = 0
    indices = range(1, dim + 1)
    for y_index in indices:
        for x_index in indices:
            for name in sorted(trace_list[trace_index].keys()):
                fig.append_trace(
                    trace_list[trace_index][name],
                    y_index,
                    x_index)
            trace_index += 1

    # Insert headers into the figure
    for j in range(dim):
        xaxis_key = 'xaxis{}'.format((dim * dim) - dim + 1 + j)
        fig['layout'][xaxis_key].update(title=headers[j])

    for j in range(dim):
        yaxis_key = 'yaxis{}'.format(1 + (dim * j))
        fig['layout'][yaxis_key].update(title=headers[j])

    hide_tick_labels_from_box_subplots(fig)

    if diag == 'histogram':
        fig['layout'].update(
            height=height, width=width,
            title=title,
            showlegend=True,
            barmode='stack')
        return fig

    else:
        fig['layout'].update(
            height=height, width=width,
            title=title,
            showlegend=True)
        return fig
Пример #25
0
def create_streamline(x,
                      y,
                      u,
                      v,
                      density=1,
                      angle=math.pi / 9,
                      arrow_scale=.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.graph_objs.Scatter
        for more information on valid kwargs call
        help(plotly.graph_objs.Scatter)

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

    Example 1: Plot simple streamline and increase arrow size
    ```
    import plotly.plotly as py
    from plotly.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)

    # Plot
    py.plot(fig, filename='streamline')
    ```

    Example 2: from nbviewer.ipython.org/github/barbagroup/AeroPython
    ```
    import plotly.plotly as py
    from plotly.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')

    # Plot
    fig['data'].append(point)
    py.plot(fig, filename='streamline')
    ```
    """
    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)
Пример #26
0
    def get_dendrogram_traces(self, X, colorscale, distfun, linkagefun,
                              hovertext):
        """
        Calculates all the elements needed for plotting a dendrogram.

        :param (ndarray) X: Matrix of observations as array of arrays
        :param (list) colorscale: Color scale for dendrogram tree clusters
        :param (function) distfun: Function to compute the pairwise distance
                                   from the observations
        :param (function) linkagefun: Function to compute the linkage matrix
                                      from the pairwise distances
        :param (list) hovertext: List of hovertext for constituent traces of dendrogram
        :rtype (tuple): Contains all the traces in the following order:
            (a) trace_list: List of Plotly trace objects for dendrogram tree
            (b) icoord: All X points of the dendrogram tree as array of arrays
                with length 4
            (c) dcoord: All Y points of the dendrogram tree as array of arrays
                with length 4
            (d) ordered_labels: leaf labels in the order they are going to
                appear on the plot
            (e) P['leaves']: left-to-right traversal of the leaves

        """
        d = distfun(X)
        Z = linkagefun(d)
        P = sch.dendrogram(Z,
                           orientation=self.orientation,
                           labels=self.labels,
                           no_plot=True)

        icoord = scp.array(P['icoord'])
        dcoord = scp.array(P['dcoord'])
        ordered_labels = scp.array(P['ivl'])
        color_list = scp.array(P['color_list'])
        colors = self.get_color_dict(colorscale)

        trace_list = []

        for i in range(len(icoord)):
            # xs and ys are arrays of 4 points that make up the '∩' shapes
            # of the dendrogram tree
            if self.orientation in ['top', 'bottom']:
                xs = icoord[i]
            else:
                xs = dcoord[i]

            if self.orientation in ['top', 'bottom']:
                ys = dcoord[i]
            else:
                ys = icoord[i]
            color_key = color_list[i]
            hovertext_label = None
            if hovertext:
                hovertext_label = hovertext[i]
            trace = graph_objs.Scatter(
                x=np.multiply(self.sign[self.xaxis], xs),
                y=np.multiply(self.sign[self.yaxis], ys),
                mode='lines',
                marker=graph_objs.scatter.Marker(color=colors[color_key]),
                text=hovertext_label,
                hoverinfo='text')

            try:
                x_index = int(self.xaxis[-1])
            except ValueError:
                x_index = ''

            try:
                y_index = int(self.yaxis[-1])
            except ValueError:
                y_index = ''

            trace['xaxis'] = 'x' + x_index
            trace['yaxis'] = 'y' + y_index

            trace_list.append(trace)

        return trace_list, icoord, dcoord, ordered_labels, P['leaves']
def create_quiver(x,
                  y,
                  u,
                  v,
                  scale=.1,
                  arrow_scale=.3,
                  angle=math.pi / 9,
                  **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 kwargs: kwargs passed through plotly.graph_objs.Scatter
        for more information on valid kwargs call
        help(plotly.graph_objs.Scatter)

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

    Example 1: Trivial Quiver
    ```
    import plotly.plotly as py
    from plotly.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)

    py.plot(fig, filename='quiver')
    ```

    Example 2: Quiver plot using meshgrid
    ```
    import plotly.plotly as py
    from plotly.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)

    # Plot
    py.plot(fig, filename='quiver')
    ```

    Example 3: Styling the quiver plot
    ```
    import plotly.plotly as py
    from plotly.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=Line(width=1))

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

    # Plot
    py.plot(fig, filename='quiver')
    ```
    """
    utils.validate_equal_length(x, y, u, v)
    utils.validate_positive_scalars(arrow_scale=arrow_scale, scale=scale)

    barb_x, barb_y = _Quiver(x, y, u, v, scale, arrow_scale, angle).get_barbs()
    arrow_x, arrow_y = _Quiver(x, y, u, v, scale, arrow_scale,
                               angle).get_quiver_arrows()
    quiver = graph_objs.Scatter(x=barb_x + arrow_x,
                                y=barb_y + arrow_y,
                                mode='lines',
                                **kwargs)

    data = [quiver]
    layout = graph_objs.Layout(hovermode='closest')

    return graph_objs.Figure(data=data, layout=layout)
Пример #28
0
def scatterplot_theme(dataframe, headers, diag, size, height, width, title,
                      index, index_vals, endpts, colormap, colormap_type,
                      **kwargs):
    """
    Refer to FigureFactory.create_scatterplotmatrix() for docstring

    Returns fig for scatterplotmatrix with both index and colormap picked

    """

    # Check if index is made of string values
    if isinstance(index_vals[0], str):
        unique_index_vals = []
        for name in index_vals:
            if name not in unique_index_vals:
                unique_index_vals.append(name)
        n_colors_len = len(unique_index_vals)

        # Convert colormap to list of n RGB tuples
        if colormap_type == 'seq':
            foo = clrs.color_parser(colormap, clrs.unlabel_rgb)
            foo = clrs.n_colors(foo[0], foo[1], n_colors_len)
            theme = clrs.color_parser(foo, clrs.label_rgb)

        if colormap_type == 'cat':
            # leave list of colors the same way
            theme = colormap

        dim = len(dataframe)
        fig = make_subplots(rows=dim, cols=dim, print_grid=False)
        trace_list = []
        legend_param = 0
        # Work over all permutations of list pairs
        for listy in dataframe:
            for listx in dataframe:
                # create a dictionary for index_vals
                unique_index_vals = {}
                for name in index_vals:
                    if name not in unique_index_vals:
                        unique_index_vals[name] = []

                c_indx = 0  # color index
                # Fill all the rest of the names into the dictionary
                for name in sorted(unique_index_vals.keys()):
                    new_listx = []
                    new_listy = []
                    for j in range(len(index_vals)):
                        if index_vals[j] == name:
                            new_listx.append(listx[j])
                            new_listy.append(listy[j])
                    # Generate trace with VISIBLE icon
                    if legend_param == 1:
                        if (listx == listy) and (diag == 'histogram'):
                            trace = graph_objs.Histogram(
                                x=new_listx,
                                marker=dict(
                                    color=theme[c_indx]),
                                showlegend=True
                            )
                        elif (listx == listy) and (diag == 'box'):
                            trace = graph_objs.Box(
                                y=new_listx,
                                name=None,
                                marker=dict(
                                    color=theme[c_indx]),
                                showlegend=True
                            )
                        else:
                            if 'marker' in kwargs:
                                kwargs['marker']['size'] = size
                                kwargs['marker']['color'] = theme[c_indx]
                                trace = graph_objs.Scatter(
                                    x=new_listx,
                                    y=new_listy,
                                    mode='markers',
                                    name=name,
                                    showlegend=True,
                                    **kwargs
                                )
                            else:
                                trace = graph_objs.Scatter(
                                    x=new_listx,
                                    y=new_listy,
                                    mode='markers',
                                    name=name,
                                    marker=dict(
                                        size=size,
                                        color=theme[c_indx]),
                                    showlegend=True,
                                    **kwargs
                                )
                    # Generate trace with INVISIBLE icon
                    else:
                        if (listx == listy) and (diag == 'histogram'):
                            trace = graph_objs.Histogram(
                                x=new_listx,
                                marker=dict(
                                    color=theme[c_indx]),
                                showlegend=False
                            )
                        elif (listx == listy) and (diag == 'box'):
                            trace = graph_objs.Box(
                                y=new_listx,
                                name=None,
                                marker=dict(
                                    color=theme[c_indx]),
                                showlegend=False
                            )
                        else:
                            if 'marker' in kwargs:
                                kwargs['marker']['size'] = size
                                kwargs['marker']['color'] = theme[c_indx]
                                trace = graph_objs.Scatter(
                                    x=new_listx,
                                    y=new_listy,
                                    mode='markers',
                                    name=name,
                                    showlegend=False,
                                    **kwargs
                                )
                            else:
                                trace = graph_objs.Scatter(
                                    x=new_listx,
                                    y=new_listy,
                                    mode='markers',
                                    name=name,
                                    marker=dict(
                                        size=size,
                                        color=theme[c_indx]),
                                    showlegend=False,
                                    **kwargs
                                )
                    # Push the trace into dictionary
                    unique_index_vals[name] = trace
                    if c_indx >= (len(theme) - 1):
                        c_indx = -1
                    c_indx += 1
                trace_list.append(unique_index_vals)
                legend_param += 1

        trace_index = 0
        indices = range(1, dim + 1)
        for y_index in indices:
            for x_index in indices:
                for name in sorted(trace_list[trace_index].keys()):
                    fig.append_trace(
                        trace_list[trace_index][name],
                        y_index,
                        x_index)
                trace_index += 1

        # Insert headers into the figure
        for j in range(dim):
            xaxis_key = 'xaxis{}'.format((dim * dim) - dim + 1 + j)
            fig['layout'][xaxis_key].update(title=headers[j])

        for j in range(dim):
            yaxis_key = 'yaxis{}'.format(1 + (dim * j))
            fig['layout'][yaxis_key].update(title=headers[j])

        hide_tick_labels_from_box_subplots(fig)

        if diag == 'histogram':
            fig['layout'].update(
                height=height, width=width,
                title=title,
                showlegend=True,
                barmode='stack')
            return fig

        elif diag == 'box':
            fig['layout'].update(
                height=height, width=width,
                title=title,
                showlegend=True)
            return fig

        else:
            fig['layout'].update(
                height=height, width=width,
                title=title,
                showlegend=True)
            return fig

    else:
        if endpts:
            intervals = utils.endpts_to_intervals(endpts)

            # Convert colormap to list of n RGB tuples
            if colormap_type == 'seq':
                foo = clrs.color_parser(colormap, clrs.unlabel_rgb)
                foo = clrs.n_colors(foo[0], foo[1], len(intervals))
                theme = clrs.color_parser(foo, clrs.label_rgb)

            if colormap_type == 'cat':
                # leave list of colors the same way
                theme = colormap

            dim = len(dataframe)
            fig = make_subplots(rows=dim, cols=dim, print_grid=False)
            trace_list = []
            legend_param = 0
            # Work over all permutations of list pairs
            for listy in dataframe:
                for listx in dataframe:
                    interval_labels = {}
                    for interval in intervals:
                        interval_labels[str(interval)] = []

                    c_indx = 0  # color index
                    # Fill all the rest of the names into the dictionary
                    for interval in intervals:
                        new_listx = []
                        new_listy = []
                        for j in range(len(index_vals)):
                            if interval[0] < index_vals[j] <= interval[1]:
                                new_listx.append(listx[j])
                                new_listy.append(listy[j])
                        # Generate trace with VISIBLE icon
                        if legend_param == 1:
                            if (listx == listy) and (diag == 'histogram'):
                                trace = graph_objs.Histogram(
                                    x=new_listx,
                                    marker=dict(
                                        color=theme[c_indx]),
                                    showlegend=True
                                )
                            elif (listx == listy) and (diag == 'box'):
                                trace = graph_objs.Box(
                                    y=new_listx,
                                    name=None,
                                    marker=dict(
                                        color=theme[c_indx]),
                                    showlegend=True
                                )
                            else:
                                if 'marker' in kwargs:
                                    kwargs['marker']['size'] = size
                                    (kwargs['marker']
                                     ['color']) = theme[c_indx]
                                    trace = graph_objs.Scatter(
                                        x=new_listx,
                                        y=new_listy,
                                        mode='markers',
                                        name=str(interval),
                                        showlegend=True,
                                        **kwargs
                                    )
                                else:
                                    trace = graph_objs.Scatter(
                                        x=new_listx,
                                        y=new_listy,
                                        mode='markers',
                                        name=str(interval),
                                        marker=dict(
                                            size=size,
                                            color=theme[c_indx]),
                                        showlegend=True,
                                        **kwargs
                                    )
                        # Generate trace with INVISIBLE icon
                        else:
                            if (listx == listy) and (diag == 'histogram'):
                                trace = graph_objs.Histogram(
                                    x=new_listx,
                                    marker=dict(
                                        color=theme[c_indx]),
                                    showlegend=False
                                )
                            elif (listx == listy) and (diag == 'box'):
                                trace = graph_objs.Box(
                                    y=new_listx,
                                    name=None,
                                    marker=dict(
                                        color=theme[c_indx]),
                                    showlegend=False
                                )
                            else:
                                if 'marker' in kwargs:
                                    kwargs['marker']['size'] = size
                                    (kwargs['marker']
                                     ['color']) = theme[c_indx]
                                    trace = graph_objs.Scatter(
                                        x=new_listx,
                                        y=new_listy,
                                        mode='markers',
                                        name=str(interval),
                                        showlegend=False,
                                        **kwargs
                                    )
                                else:
                                    trace = graph_objs.Scatter(
                                        x=new_listx,
                                        y=new_listy,
                                        mode='markers',
                                        name=str(interval),
                                        marker=dict(
                                            size=size,
                                            color=theme[c_indx]),
                                        showlegend=False,
                                        **kwargs
                                    )
                        # Push the trace into dictionary
                        interval_labels[str(interval)] = trace
                        if c_indx >= (len(theme) - 1):
                            c_indx = -1
                        c_indx += 1
                    trace_list.append(interval_labels)
                    legend_param += 1

            trace_index = 0
            indices = range(1, dim + 1)
            for y_index in indices:
                for x_index in indices:
                    for interval in intervals:
                        fig.append_trace(
                            trace_list[trace_index][str(interval)],
                            y_index,
                            x_index)
                    trace_index += 1

            # Insert headers into the figure
            for j in range(dim):
                xaxis_key = 'xaxis{}'.format((dim * dim) - dim + 1 + j)
                fig['layout'][xaxis_key].update(title=headers[j])
            for j in range(dim):
                yaxis_key = 'yaxis{}'.format(1 + (dim * j))
                fig['layout'][yaxis_key].update(title=headers[j])

            hide_tick_labels_from_box_subplots(fig)

            if diag == 'histogram':
                fig['layout'].update(
                    height=height, width=width,
                    title=title,
                    showlegend=True,
                    barmode='stack')
                return fig

            elif diag == 'box':
                fig['layout'].update(
                    height=height, width=width,
                    title=title,
                    showlegend=True)
                return fig

            else:
                fig['layout'].update(
                    height=height, width=width,
                    title=title,
                    showlegend=True)
                return fig

        else:
            theme = colormap

            # add a copy of rgb color to theme if it contains one color
            if len(theme) <= 1:
                theme.append(theme[0])

            color = []
            for incr in range(len(theme)):
                color.append([1. / (len(theme) - 1) * incr, theme[incr]])

            dim = len(dataframe)
            fig = make_subplots(rows=dim, cols=dim, print_grid=False)
            trace_list = []
            legend_param = 0
            # Run through all permutations of list pairs
            for listy in dataframe:
                for listx in dataframe:
                    # Generate trace with VISIBLE icon
                    if legend_param == 1:
                        if (listx == listy) and (diag == 'histogram'):
                            trace = graph_objs.Histogram(
                                x=listx,
                                marker=dict(
                                    color=theme[0]),
                                showlegend=False
                            )
                        elif (listx == listy) and (diag == 'box'):
                            trace = graph_objs.Box(
                                y=listx,
                                marker=dict(
                                    color=theme[0]),
                                showlegend=False
                            )
                        else:
                            if 'marker' in kwargs:
                                kwargs['marker']['size'] = size
                                kwargs['marker']['color'] = index_vals
                                kwargs['marker']['colorscale'] = color
                                kwargs['marker']['showscale'] = True
                                trace = graph_objs.Scatter(
                                    x=listx,
                                    y=listy,
                                    mode='markers',
                                    showlegend=False,
                                    **kwargs
                                )
                            else:
                                trace = graph_objs.Scatter(
                                    x=listx,
                                    y=listy,
                                    mode='markers',
                                    marker=dict(
                                        size=size,
                                        color=index_vals,
                                        colorscale=color,
                                        showscale=True),
                                    showlegend=False,
                                    **kwargs
                                )
                    # Generate trace with INVISIBLE icon
                    else:
                        if (listx == listy) and (diag == 'histogram'):
                            trace = graph_objs.Histogram(
                                x=listx,
                                marker=dict(
                                    color=theme[0]),
                                showlegend=False
                            )
                        elif (listx == listy) and (diag == 'box'):
                            trace = graph_objs.Box(
                                y=listx,
                                marker=dict(
                                    color=theme[0]),
                                showlegend=False
                            )
                        else:
                            if 'marker' in kwargs:
                                kwargs['marker']['size'] = size
                                kwargs['marker']['color'] = index_vals
                                kwargs['marker']['colorscale'] = color
                                kwargs['marker']['showscale'] = False
                                trace = graph_objs.Scatter(
                                    x=listx,
                                    y=listy,
                                    mode='markers',
                                    showlegend=False,
                                    **kwargs
                                )
                            else:
                                trace = graph_objs.Scatter(
                                    x=listx,
                                    y=listy,
                                    mode='markers',
                                    marker=dict(
                                        size=size,
                                        color=index_vals,
                                        colorscale=color,
                                        showscale=False),
                                    showlegend=False,
                                    **kwargs
                                )
                    # Push the trace into list
                    trace_list.append(trace)
                    legend_param += 1

            trace_index = 0
            indices = range(1, dim + 1)
            for y_index in indices:
                for x_index in indices:
                    fig.append_trace(trace_list[trace_index],
                                     y_index,
                                     x_index)
                    trace_index += 1

            # Insert headers into the figure
            for j in range(dim):
                xaxis_key = 'xaxis{}'.format((dim * dim) - dim + 1 + j)
                fig['layout'][xaxis_key].update(title=headers[j])
            for j in range(dim):
                yaxis_key = 'yaxis{}'.format(1 + (dim * j))
                fig['layout'][yaxis_key].update(title=headers[j])

            hide_tick_labels_from_box_subplots(fig)

            if diag == 'histogram':
                fig['layout'].update(
                    height=height, width=width,
                    title=title,
                    showlegend=True,
                    barmode='stack')
                return fig

            elif diag == 'box':
                fig['layout'].update(
                    height=height, width=width,
                    title=title,
                    showlegend=True)
                return fig

            else:
                fig['layout'].update(
                    height=height, width=width,
                    title=title,
                    showlegend=True)
                return fig
Пример #29
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.graph_objs.Scatter
        for more information on valid kwargs call
        help(plotly.graph_objs.Scatter)

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

    Example 1: Plot simple streamline and increase arrow size

    >>> from plotly.figure_factory import create_streamline
    >>> import plotly.graph_objects as go
    >>> 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.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 = go.Scatter(x=[x_s], y=[y_s], mode='markers',
    ...                    marker_size=14, name='source point')

    >>> fig.add_trace(point) # doctest: +SKIP
    >>> 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)
Пример #30
0
def view_image(w):
    x_data = [1, 2, 3]
    x1 = [i + w for i in x_data]
    fig1 = go.Scatter(x=x1, y=[4, 5, 6])
    fig2 = go.Scatter(x=x_data, y=[4, 5, 6])
    iplot([fig1, fig2])