def test_get_module_import_exception(self):
        # Get module that raises an exception on import
        module_str = "plotly.tests.test_core." "test_optional_imports.exploding_module"

        if sys.version_info >= (3, 4):
            with self.assertLogs("_plotly_utils.optional_imports",
                                 level="ERROR") as cm:
                module = get_module(module_str)

            # No exception should be raised and None should be returned
            self.assertIsNone(module)

            # Check logging level and log message
            expected_start = ("ERROR:_plotly_utils.optional_imports:"
                              "Error importing optional module " + module_str)

            self.assertEqual(cm.output[0][:len(expected_start)],
                             expected_start)

            # Check that exception message is included after log message
            expected_end = "Boom!"
            self.assertEqual(cm.output[0][-len(expected_end):], expected_end)
        else:
            # Don't check logging
            module = get_module(module_str)

            # No exception should be raised and None should be returned
            self.assertIsNone(module)
示例#2
0
    def test_get_module_import_exception(self):
        # Get module that raises an exception on import
        module_str = ('plotly.tests.test_core.'
                      'test_optional_imports.exploding_module')

        if sys.version_info.major == 3 and sys.version_info.minor >= 4:
            with self.assertLogs('_plotly_utils.optional_imports', level='ERROR') as cm:
                module = get_module(module_str)

            # No exception should be raised and None should be returned
            self.assertIsNone(module)

            # Check logging level and log message
            expected_start = ('ERROR:_plotly_utils.optional_imports:'
                              'Error importing optional module ' + module_str)

            self.assertEqual(
                cm.output[0][:len(expected_start)], expected_start)

            # Check that exception message is included after log message
            expected_end = 'Boom!'
            self.assertEqual(
                cm.output[0][-len(expected_end):], expected_end)
        else:
            # Don't check logging
            module = get_module(module_str)

            # No exception should be raised and None should be returned
            self.assertIsNone(module)
示例#3
0
 def our_mpl_to_plotly(fig):
     matplotlylib = optional_imports.get_module('plotly.matplotlylib')
     if matplotlylib:
         renderer = matplotlylib.PlotlyRenderer()
         matplotlylib.Exporter(renderer, close_mpl=False).run(fig)
         x_ticks = list(renderer.current_mpl_ax.get_xticklabels())
         if x_ticks:
             try:
                 # check if all values can be cast to float
                 values = [float(t.get_text().replace('−', '-')) for t in x_ticks]
             except:
                 try:
                     renderer.plotly_fig['layout']['xaxis1'].update({
                         'ticktext': [t.get_text() for t in x_ticks],
                         'tickvals': [t.get_position()[0] for t in x_ticks],
                     })
                 except:
                     pass
         y_ticks = list(renderer.current_mpl_ax.get_yticklabels())
         if y_ticks:
             try:
                 # check if all values can be cast to float
                 values = [float(t.get_text().replace('−', '-')) for t in y_ticks]
             except:
                 try:
                     renderer.plotly_fig['layout']['yaxis1'].update({
                         'ticktext': [t.get_text() for t in y_ticks],
                         'tickvals': [t.get_position()[1] for t in y_ticks],
                     })
                 except:
                     pass
         return renderer.plotly_fig
示例#4
0
 def our_mpl_to_plotly(fig):
     matplotlylib = optional_imports.get_module(
         'plotly.matplotlylib')
     if matplotlylib:
         renderer = matplotlylib.PlotlyRenderer()
         matplotlylib.Exporter(renderer,
                               close_mpl=False).run(fig)
         return renderer.plotly_fig
示例#5
0
def enable_mpl_offline(
    resize=False,
    strip_style=False,
    verbose=False,
    show_link=False,
    link_text="Export to plot.ly",
    validate=True,
):
    """
    Convert mpl plots to locally hosted HTML documents.

    This function should be used with the inline matplotlib backend
    that ships with IPython that can be enabled with `%pylab inline`
    or `%matplotlib inline`. This works by adding an HTML formatter
    for Figure objects; the existing SVG/PNG formatters will remain
    enabled.

    (idea taken from `mpld3._display.enable_notebook`)

    Example:
    ```
    from plotly.offline import enable_mpl_offline
    import matplotlib.pyplot as plt

    enable_mpl_offline()

    fig = plt.figure()
    x = [10, 15, 20, 25, 30]
    y = [100, 250, 200, 150, 300]
    plt.plot(x, y, "o")
    fig
    ```
    """
    init_notebook_mode()
    ipython = get_module("IPython")
    matplotlib = get_module("matplotlib")

    ip = ipython.core.getipython.get_ipython()
    formatter = ip.display_formatter.formatters["text/html"]
    formatter.for_type(
        matplotlib.figure.Figure,
        lambda fig: iplot_mpl(
            fig, resize, strip_style, verbose, show_link, link_text, validate
        ),
    )
示例#6
0
def mpl_to_plotly(fig, resize=False, strip_style=False, verbose=False):
    """Convert a matplotlib figure to plotly dictionary and send.

    All available information about matplotlib visualizations are stored
    within a matplotlib.figure.Figure object. You can create a plot in python
    using matplotlib, store the figure object, and then pass this object to
    the fig_to_plotly function. In the background, mplexporter is used to
    crawl through the mpl figure object for appropriate information. This
    information is then systematically sent to the PlotlyRenderer which
    creates the JSON structure used to make plotly visualizations. Finally,
    these dictionaries are sent to plotly and your browser should open up a
    new tab for viewing! Optionally, if you're working in IPython, you can
    set notebook=True and the PlotlyRenderer will call plotly.iplot instead
    of plotly.plot to have the graph appear directly in the IPython notebook.

    Note, this function gives the user access to a simple, one-line way to
    render an mpl figure in plotly. If you need to trouble shoot, you can do
    this step manually by NOT running this fuction and entereing the following:

    ===========================================================================
    from plotly.matplotlylib import mplexporter, PlotlyRenderer

    # create an mpl figure and store it under a varialble 'fig'

    renderer = PlotlyRenderer()
    exporter = mplexporter.Exporter(renderer)
    exporter.run(fig)
    ===========================================================================

    You can then inspect the JSON structures by accessing these:

    renderer.layout -- a plotly layout dictionary
    renderer.data -- a list of plotly data dictionaries
    """
    matplotlylib = optional_imports.get_module("plotly.matplotlylib")
    if matplotlylib:
        renderer = matplotlylib.PlotlyRenderer()
        matplotlylib.Exporter(renderer).run(fig)
        if resize:
            renderer.resize()
        if strip_style:
            renderer.strip_style()
        if verbose:
            print(renderer.msg)
        return renderer.plotly_fig
    else:
        warnings.warn(
            "To use Plotly's matplotlylib functionality, you'll need to have "
            "matplotlib successfully installed with all of its dependencies. "
            "You're getting this error because matplotlib or one of its "
            "dependencies doesn't seem to be installed correctly."
        )
示例#7
0
文件: tools.py 项目: plotly/plotly.py
def mpl_to_plotly(fig, resize=False, strip_style=False, verbose=False):
    """Convert a matplotlib figure to plotly dictionary and send.

    All available information about matplotlib visualizations are stored
    within a matplotlib.figure.Figure object. You can create a plot in python
    using matplotlib, store the figure object, and then pass this object to
    the fig_to_plotly function. In the background, mplexporter is used to
    crawl through the mpl figure object for appropriate information. This
    information is then systematically sent to the PlotlyRenderer which
    creates the JSON structure used to make plotly visualizations. Finally,
    these dictionaries are sent to plotly and your browser should open up a
    new tab for viewing! Optionally, if you're working in IPython, you can
    set notebook=True and the PlotlyRenderer will call plotly.iplot instead
    of plotly.plot to have the graph appear directly in the IPython notebook.

    Note, this function gives the user access to a simple, one-line way to
    render an mpl figure in plotly. If you need to trouble shoot, you can do
    this step manually by NOT running this fuction and entereing the following:

    ===========================================================================
    from plotly.matplotlylib import mplexporter, PlotlyRenderer

    # create an mpl figure and store it under a varialble 'fig'

    renderer = PlotlyRenderer()
    exporter = mplexporter.Exporter(renderer)
    exporter.run(fig)
    ===========================================================================

    You can then inspect the JSON structures by accessing these:

    renderer.layout -- a plotly layout dictionary
    renderer.data -- a list of plotly data dictionaries
    """
    matplotlylib = optional_imports.get_module('plotly.matplotlylib')
    if matplotlylib:
        renderer = matplotlylib.PlotlyRenderer()
        matplotlylib.Exporter(renderer).run(fig)
        if resize:
            renderer.resize()
        if strip_style:
            renderer.strip_style()
        if verbose:
            print(renderer.msg)
        return renderer.plotly_fig
    else:
        warnings.warn(
            "To use Plotly's matplotlylib functionality, you'll need to have "
            "matplotlib successfully installed with all of its dependencies. "
            "You're getting this error because matplotlib or one of its "
            "dependencies doesn't seem to be installed correctly.")
示例#8
0
def enable_mpl_offline(resize=False, strip_style=False,
                       verbose=False, show_link=False,
                       link_text='Export to plot.ly', validate=True):
    """
    Convert mpl plots to locally hosted HTML documents.

    This function should be used with the inline matplotlib backend
    that ships with IPython that can be enabled with `%pylab inline`
    or `%matplotlib inline`. This works by adding an HTML formatter
    for Figure objects; the existing SVG/PNG formatters will remain
    enabled.

    (idea taken from `mpld3._display.enable_notebook`)

    Example:
    ```
    from plotly.offline import enable_mpl_offline
    import matplotlib.pyplot as plt

    enable_mpl_offline()

    fig = plt.figure()
    x = [10, 15, 20, 25, 30]
    y = [100, 250, 200, 150, 300]
    plt.plot(x, y, "o")
    fig
    ```
    """
    init_notebook_mode()
    ipython = get_module('IPython')
    matplotlib = get_module('matplotlib')

    ip = ipython.core.getipython.get_ipython()
    formatter = ip.display_formatter.formatters['text/html']
    formatter.for_type(matplotlib.figure.Figure,
                       lambda fig: iplot_mpl(fig, resize, strip_style, verbose,
                                             show_link, link_text, validate))
示例#9
0
    def _update_plotly_renderers():
        if PatchedMatplotlib._matplotlylib and PatchedMatplotlib._plotly_renderer:
            return True

        # create plotly renderer
        try:
            from plotly import optional_imports
            PatchedMatplotlib._matplotlylib = optional_imports.get_module(
                'plotly.matplotlylib')
            PatchedMatplotlib._plotly_renderer = PatchedMatplotlib._matplotlylib.PlotlyRenderer(
            )
        except Exception:
            return False

        return True
示例#10
0
def init_notebook_mode(connected=False):
    """
    Initialize plotly.js in the browser if it hasn't been loaded into the DOM
    yet. This is an idempotent method and can and should be called from any
    offline methods that require plotly.js to be loaded into the notebook dom.

    Keyword arguments:

    connected (default=False) -- If True, the plotly.js library will be loaded
    from an online CDN. If False, the plotly.js library will be loaded locally
    from the plotly python package

    Use `connected=True` if you want your notebooks to have smaller file sizes.
    In the case where `connected=False`, the entirety of the plotly.js library
    will be loaded into the notebook, which will result in a file-size increase
    of a couple megabytes. Additionally, because the library will be downloaded
    from the web, you and your viewers must be connected to the internet to be
    able to view charts within this notebook.

    Use `connected=False` if you want you and your collaborators to be able to
    create and view these charts regardless of the availability of an internet
    connection. This is the default option since it is the most predictable.
    Note that under this setting the library will be included inline inside
    your notebook, resulting in much larger notebook sizes compared to the case
    where `connected=True`.
    """
    import plotly.io as pio

    ipython = get_module("IPython")
    if not ipython:
        raise ImportError("`iplot` can only run inside an IPython Notebook.")

    if connected:
        pio.renderers.default = "plotly_mimetype+notebook_connected"
    else:
        pio.renderers.default = "plotly_mimetype+notebook"

    # Trigger immediate activation of notebook. This way the plotly.js
    # library reference is available to the notebook immediately
    pio.renderers._activate_pending_renderers()
示例#11
0
def init_notebook_mode(connected=False):
    """
    Initialize plotly.js in the browser if it hasn't been loaded into the DOM
    yet. This is an idempotent method and can and should be called from any
    offline methods that require plotly.js to be loaded into the notebook dom.

    Keyword arguments:

    connected (default=False) -- If True, the plotly.js library will be loaded
    from an online CDN. If False, the plotly.js library will be loaded locally
    from the plotly python package

    Use `connected=True` if you want your notebooks to have smaller file sizes.
    In the case where `connected=False`, the entirety of the plotly.js library
    will be loaded into the notebook, which will result in a file-size increase
    of a couple megabytes. Additionally, because the library will be downloaded
    from the web, you and your viewers must be connected to the internet to be
    able to view charts within this notebook.

    Use `connected=False` if you want you and your collaborators to be able to
    create and view these charts regardless of the availability of an internet
    connection. This is the default option since it is the most predictable.
    Note that under this setting the library will be included inline inside
    your notebook, resulting in much larger notebook sizes compared to the case
    where `connected=True`.
    """
    import plotly.io as pio
    ipython = get_module('IPython')
    if not ipython:
        raise ImportError('`iplot` can only run inside an IPython Notebook.')

    if connected:
        pio.renderers.default = 'plotly_mimetype+notebook_connected'
    else:
        pio.renderers.default = 'plotly_mimetype+notebook'

    # Trigger immediate activation of notebook. This way the plotly.js
    # library reference is available to the notebook immediately
    pio.renderers._activate_pending_renderers()
示例#12
0
from __future__ import absolute_import

import pytest

from plotly import optional_imports
from plotly.tests.test_optional.optional_utils import run_fig
from plotly.tests.test_optional.test_matplotlylib.data.data import *

matplotlylib = optional_imports.get_module("plotly.matplotlylib")

if matplotlylib:
    import matplotlib.pyplot as plt


@pytest.mark.skip
def test_line_data():
    fig, ax = plt.subplots()
    ax.plot(D["x1"], D["y1"])
    renderer = run_fig(fig)
    for xi, xf, yi, yf in zip(
            renderer.plotly_fig["data"][0]["x"],
            D["x1"],
            renderer.plotly_fig["data"][0]["y"],
            D["y1"],
    ):
        assert xi == xf, (str(renderer.plotly_fig["data"][0]["x"]) +
                          " is not " + str(D["x1"]))
        assert yi == yf, (str(renderer.plotly_fig["data"][0]["y"]) +
                          " is not " + str(D["y1"]))

    def test_get_module_exists(self):
        import math

        module = get_module("math")
        self.assertIsNotNone(module)
        self.assertEqual(math, module)
 def test_get_module_does_not_exist(self):
     module = get_module("hoopla")
     self.assertIsNone(module)
示例#15
0
def create_ternary_contour(
    coordinates,
    values,
    pole_labels=["a", "b", "c"],
    width=500,
    height=500,
    ncontours=None,
    showscale=False,
    coloring=None,
    colorscale="Bluered",
    linecolor=None,
    title=None,
    interp_mode="ilr",
    showmarkers=False,
):
    """
    Ternary contour plot.

    Parameters
    ----------

    coordinates : list or ndarray
        Barycentric coordinates of shape (2, N) or (3, N) where N is the
        number of data points. The sum of the 3 coordinates is expected
        to be 1 for all data points.
    values : array-like
        Data points of field to be represented as contours.
    pole_labels : str, default ['a', 'b', 'c']
        Names of the three poles of the triangle.
    width : int
        Figure width.
    height : int
        Figure height.
    ncontours : int or None
        Number of contours to display (determined automatically if None).
    showscale : bool, default False
        If True, a colorbar showing the color scale is displayed.
    coloring : None or 'lines'
        How to display contour. Filled contours if None, lines if ``lines``.
    colorscale : None or str (Plotly colormap)
        colorscale of the contours.
    linecolor : None or rgb color
        Color used for lines. ``colorscale`` has to be set to None, otherwise
        line colors are determined from ``colorscale``.
    title : str or None
        Title of ternary plot
    interp_mode : 'ilr' (default) or 'cartesian'
        Defines how data are interpolated to compute contours. If 'irl',
        ILR (Isometric Log-Ratio) of compositional data is performed. If
        'cartesian', contours are determined in Cartesian space.
    showmarkers : bool, default False
        If True, markers corresponding to input compositional points are
        superimposed on contours, using the same colorscale.

    Examples
    ========

    Example 1: ternary contour plot with filled contours

    >>> import plotly.figure_factory as ff
    >>> import numpy as np
    >>> # Define coordinates
    >>> a, b = np.mgrid[0:1:20j, 0:1:20j]
    >>> mask = a + b <= 1
    >>> a = a[mask].ravel()
    >>> b = b[mask].ravel()
    >>> c = 1 - a - b
    >>> # Values to be displayed as contours
    >>> z = a * b * c
    >>> fig = ff.create_ternarycontour(np.stack((a, b, c)), z)
    >>> fig.show()

    It is also possible to give only two barycentric coordinates for each
    point, since the sum of the three coordinates is one:

    >>> fig = ff.create_ternarycontour(np.stack((a, b)), z)


    Example 2: ternary contour plot with line contours

    >>> fig = ff.create_ternarycontour(np.stack((a, b, c)), z, coloring='lines')

    Example 3: customize number of contours

    >>> fig = ff.create_ternarycontour(np.stack((a, b, c)), z, ncontours=8)

    Example 4: superimpose contour plot and original data as markers

    >>> fig = ff.create_ternarycontour(np.stack((a, b, c)), z, coloring='lines',
                                   showmarkers=True)

    Example 5: customize title and pole labels

    >>> fig = ff.create_ternarycontour(np.stack((a, b, c)), z,
    ...                               title='Ternary plot',
    ...                               pole_labels=['clay', 'quartz', 'fledspar'])
    """
    if scipy_interp is None:
        raise ImportError("""\
    The create_ternary_contour figure factory requires the scipy package""")
    sk_measure = optional_imports.get_module("skimage")
    if sk_measure is None:
        raise ImportError("""\
    The create_ternary_contour figure factory requires the scikit-image
    package""")
    if colorscale is None:
        showscale = False
    if ncontours is None:
        ncontours = 5
    coordinates = _prepare_barycentric_coord(coordinates)
    v_min, v_max = values.min(), values.max()
    grid_z, gr_x, gr_y = _compute_grid(coordinates,
                                       values,
                                       interp_mode=interp_mode)

    layout = _ternary_layout(pole_labels=pole_labels,
                             width=width,
                             height=height,
                             title=title)

    contour_trace, discrete_cm = _contour_trace(
        gr_x,
        gr_y,
        grid_z,
        ncontours=ncontours,
        colorscale=colorscale,
        linecolor=linecolor,
        interp_mode=interp_mode,
        coloring=coloring,
        v_min=v_min,
        v_max=v_max,
    )

    fig = go.Figure(data=contour_trace, layout=layout)

    opacity = 1 if showmarkers else 0
    a, b, c = coordinates
    hovertemplate = (pole_labels[0] + ": %{a:.3f}<br>" + pole_labels[1] +
                     ": %{b:.3f}<br>" + pole_labels[2] + ": %{c:.3f}<br>"
                     "z: %{marker.color:.3f}<extra></extra>")

    fig.add_scatterternary(
        a=a,
        b=b,
        c=c,
        mode="markers",
        marker={
            "color": values,
            "colorscale": colorscale,
            "line": {
                "color": "rgb(120, 120, 120)",
                "width": int(coloring != "lines")
            },
        },
        opacity=opacity,
        hovertemplate=hovertemplate,
    )
    if showscale:
        if not showmarkers:
            colorscale = discrete_cm
        colorbar = dict({
            "type": "scatterternary",
            "a": [None],
            "b": [None],
            "c": [None],
            "marker": {
                "cmin": values.min(),
                "cmax": values.max(),
                "colorscale": colorscale,
                "showscale": True,
            },
            "mode": "markers",
        })
        fig.add_trace(colorbar)

    return fig
示例#16
0
from __future__ import absolute_import
import plotly.colors as clrs
from plotly.graph_objs import graph_objs as go
from plotly import exceptions, optional_imports
from plotly import optional_imports
from plotly.graph_objs import graph_objs as go

np = optional_imports.get_module('numpy')
sk_measure = optional_imports.get_module('skimage.measure')
scipy_interp = optional_imports.get_module('scipy.interpolate')

# -------------------------- Layout ------------------------------


def _ternary_layout(title='Ternary contour plot',
                    width=550,
                    height=525,
                    pole_labels=['a', 'b', 'c']):
    """
    Layout of ternary contour plot, to be passed to ``go.FigureWidget``
    object.

    Parameters
    ==========
    title : str or None
        Title of ternary plot
    width : int
        Figure width.
    height : int
        Figure height.
    pole_labels : str, default ['a', 'b', 'c']
示例#17
0
    server.
"""
from __future__ import absolute_import

import time
import warnings
import os
import webbrowser

import uuid
from requests.compat import json as _json
import plotly
from plotly import optional_imports, tools, utils
from plotly.exceptions import PlotlyError

ipython = optional_imports.get_module('IPython')
ipython_display = optional_imports.get_module('IPython.display')

from plotly.offline.offline import (get_image_download_script,
                                    get_plotlyjs)

def check_offline():
    return plotly.offline.offline.__PLOTLY_OFFLINE_INITIALIZED

__IMAGE_FORMATS = plotly.offline.offline.__IMAGE_FORMATS


def _plot_html(figure_or_data, config, validate, default_width,
               default_height, global_requirejs):
    # force no validation if frames is in the call
    # TODO - add validation for frames in call - #605
示例#18
0
"""
dashboard_objs
==========

A module for creating and manipulating dashboard content. You can create
a Dashboard object, insert boxes, swap boxes, remove a box and get an HTML
preview of the Dashboard.
```
"""

import pprint

from plotly import exceptions, optional_imports
from plotly.utils import node_generator

IPython = optional_imports.get_module('IPython')

# default parameters for HTML preview
MASTER_WIDTH = 500
MASTER_HEIGHT = 500
FONT_SIZE = 9


ID_NOT_VALID_MESSAGE = (
    "Your box_id must be a number in your dashboard. To view a "
    "representation of your dashboard run get_preview()."
)


def _empty_box():
    empty_box = {
 def test_get_module_exists_submodule(self):
     import requests.sessions
     module = get_module('requests.sessions')
     self.assertIsNotNone(module)
     self.assertEqual(requests.sessions, module)
示例#20
0
from __future__ import absolute_import

from plotly import optional_imports

# Require that numpy exists for figure_factory
np = optional_imports.get_module('numpy')
if np is None:
    raise ImportError("""\
The figure factory module requires the numpy package""")


from plotly.figure_factory._2d_density import create_2d_density
from plotly.figure_factory._annotated_heatmap import create_annotated_heatmap
from plotly.figure_factory._bullet import create_bullet
from plotly.figure_factory._candlestick import create_candlestick
from plotly.figure_factory._dendrogram import create_dendrogram
from plotly.figure_factory._distplot import create_distplot
from plotly.figure_factory._facet_grid import create_facet_grid
from plotly.figure_factory._gantt import create_gantt
from plotly.figure_factory._ohlc import create_ohlc
from plotly.figure_factory._quiver import create_quiver
from plotly.figure_factory._scatterplot import create_scatterplotmatrix
from plotly.figure_factory._streamline import create_streamline
from plotly.figure_factory._table import create_table
from plotly.figure_factory._ternary_contour import create_ternary_contour
from plotly.figure_factory._trisurf import create_trisurf
from plotly.figure_factory._violin import create_violin
if optional_imports.get_module('pandas') is not None:
    from plotly.figure_factory._county_choropleth import create_choropleth
示例#21
0
文件: tools.py 项目: plotly/plotly.py
                 'Viridis': ['rgb(68,1,84)', 'rgb(253,231,37)']}

# color constants for violin plot
DEFAULT_FILLCOLOR = '#1f77b4'
DEFAULT_HISTNORM = 'probability density'
ALTERNATIVE_HISTNORM = 'probability'


# Warning format
def warning_on_one_line(message, category, filename, lineno,
                        file=None, line=None):
    return '%s:%s: %s:\n\n%s\n\n' % (filename, lineno, category.__name__,
                                     message)
warnings.formatwarning = warning_on_one_line

ipython_core_display = optional_imports.get_module('IPython.core.display')
sage_salvus = optional_imports.get_module('sage_salvus')


### mpl-related tools ###
def mpl_to_plotly(fig, resize=False, strip_style=False, verbose=False):
    """Convert a matplotlib figure to plotly dictionary and send.

    All available information about matplotlib visualizations are stored
    within a matplotlib.figure.Figure object. You can create a plot in python
    using matplotlib, store the figure object, and then pass this object to
    the fig_to_plotly function. In the background, mplexporter is used to
    crawl through the mpl figure object for appropriate information. This
    information is then systematically sent to the PlotlyRenderer which
    creates the JSON structure used to make plotly visualizations. Finally,
    these dictionaries are sent to plotly and your browser should open up a
 def test_get_module_does_not_exist(self):
     module = get_module('hoopla')
     self.assertIsNone(module)
示例#23
0
def iplot(figure_or_data, show_link=False, link_text='Export to plot.ly',
          validate=True, image=None, filename='plot_image', image_width=800,
          image_height=600, config=None, auto_play=True, animation_opts=None):
    """
    Draw plotly graphs inside an IPython or Jupyter notebook

    figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or
                      dict or list that describes a Plotly graph.
                      See https://plot.ly/python/ for examples of
                      graph descriptions.

    Keyword arguments:
    show_link (default=False) -- display a link in the bottom-right corner of
                                of the chart that will export the chart to
                                Plotly Cloud or Plotly Enterprise
    link_text (default='Export to plot.ly') -- the text of export link
    validate (default=True) -- validate that all of the keys in the figure
                               are valid? omit if your version of plotly.js
                               has become outdated with your version of
                               graph_reference.json or if you need to include
                               extra, unnecessary keys in your figure.
    image (default=None |'png' |'jpeg' |'svg' |'webp') -- This parameter sets
        the format of the image to be downloaded, if we choose to download an
        image. This parameter has a default value of None indicating that no
        image should be downloaded. Please note: for higher resolution images
        and more export options, consider using plotly.io.write_image. See
        https://plot.ly/python/static-image-export/ for more details.
    filename (default='plot') -- Sets the name of the file your image
        will be saved to. The extension should not be included.
    image_height (default=600) -- Specifies the height of the image in `px`.
    image_width (default=800) -- Specifies the width of the image in `px`.
    config (default=None) -- Plot view options dictionary. Keyword arguments
        `show_link` and `link_text` set the associated options in this
        dictionary if it doesn't contain them already.
    auto_play (default=True) -- Whether to automatically start the animation
        sequence if the figure contains frames. Has no effect if the figure
        does not contain frames.
    animation_opts (default=None) -- dict of custom animation parameters to be
        passed to the function Plotly.animate in Plotly.js. See
        https://github.com/plotly/plotly.js/blob/master/src/plots/animation_attributes.js
        for available options.  Has no effect if the figure
        does not contain frames, or auto_play is False.

    Example:
    ```
    from plotly.offline import init_notebook_mode, iplot
    init_notebook_mode()
    iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}])
    # We can also download an image of the plot by setting the image to the
    format you want. e.g. `image='png'`
    iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}], image='png')
    ```

    animation_opts Example:
    ```
    from plotly.offline import iplot
    figure = {'data': [{'x': [0, 1], 'y': [0, 1]}],
              'layout': {'xaxis': {'range': [0, 5], 'autorange': False},
                         'yaxis': {'range': [0, 5], 'autorange': False},
                         'title': 'Start Title'},
              'frames': [{'data': [{'x': [1, 2], 'y': [1, 2]}]},
                         {'data': [{'x': [1, 4], 'y': [1, 4]}]},
                         {'data': [{'x': [3, 4], 'y': [3, 4]}],
                          'layout': {'title': 'End Title'}}]}
    iplot(figure,animation_opts="{frame: {duration: 1}}")
    ```
    """
    import plotly.io as pio

    ipython = get_module('IPython')
    if not ipython:
        raise ImportError('`iplot` can only run inside an IPython Notebook.')

    config = dict(config) if config else {}
    config.setdefault('showLink', show_link)
    config.setdefault('linkText', link_text)

    # Get figure
    figure = tools.return_figure_from_figure_or_data(figure_or_data, validate)

    # Handle image request
    post_script = build_save_image_post_script(
        image, filename, image_height, image_width, 'iplot')

    # Show figure
    pio.show(figure,
             validate=validate,
             config=config,
             auto_play=auto_play,
             post_script=post_script,
             animation_opts=animation_opts)
示例#24
0
import numpy as np
import os
import pandas as pd
import warnings

from math import log, floor
from numbers import Number

from plotly import optional_imports
import plotly.colors as clrs
from plotly.figure_factory import utils
from plotly.exceptions import PlotlyError

pd.options.mode.chained_assignment = None

shapely = optional_imports.get_module('shapely')
shapefile = optional_imports.get_module('shapefile')
gp = optional_imports.get_module('geopandas')


def _create_us_counties_df(st_to_state_name_dict, state_to_st_dict):
    # URLS
    abs_file_path = os.path.realpath(__file__)
    abs_dir_path = os.path.dirname(abs_file_path)

    abs_plotly_dir_path = os.path.dirname(abs_dir_path)

    abs_package_data_dir_path = os.path.join(abs_plotly_dir_path,
                                             'package_data')

    shape_pre2010 = 'gz_2010_us_050_00_500k.shp'
示例#25
0
import sys
import threading
import warnings
from copy import copy
from contextlib import contextmanager

import requests
import retrying
from six import string_types

import plotly
from plotly.files import PLOTLY_DIR, ensure_writable_plotly_dir
from plotly.io._utils import validate_coerce_fig_to_dict
from plotly.optional_imports import get_module

psutil = get_module('psutil')

# Valid image format constants
# ----------------------------
valid_formats = ('png', 'jpeg', 'webp', 'svg', 'pdf', 'eps')
format_conversions = {fmt: fmt
                      for fmt in valid_formats}
format_conversions.update({'jpg': 'jpeg'})


# Utility functions
# -----------------
def raise_format_value_error(val):
    raise ValueError("""
Invalid value of type {typ} receive as an image format specification.
    Received value: {v}
示例#26
0
# -*- coding: utf-8 -*-

from __future__ import absolute_import

from collections import OrderedDict

from plotly import exceptions, optional_imports
from plotly.graph_objs import graph_objs

# Optional imports, may be None for users that only use our core functionality.
np = optional_imports.get_module("numpy")
scp = optional_imports.get_module("scipy")
sch = optional_imports.get_module("scipy.cluster.hierarchy")
scs = optional_imports.get_module("scipy.spatial")


def create_dendrogram(
    X,
    orientation="bottom",
    labels=None,
    colorscale=None,
    distfun=None,
    linkagefun=lambda x: sch.linkage(x, "complete"),
    hovertext=None,
    color_threshold=None,
):
    """
    BETA function that returns a dendrogram Plotly figure object.

    :param (ndarray) X: Matrix of observations as array of arrays
    :param (str) orientation: 'top', 'right', 'bottom', or 'left'
示例#27
0
from __future__ import absolute_import

from plotly import colors, exceptions, optional_imports
from plotly.figure_factory import utils
from plotly.tools import make_subplots

import math
from numbers import Number

pd = optional_imports.get_module('pandas')

TICK_COLOR = '#969696'
AXIS_TITLE_COLOR = '#0f0f0f'
AXIS_TITLE_SIZE = 12
GRID_COLOR = '#ffffff'
LEGEND_COLOR = '#efefef'
PLOT_BGCOLOR = '#ededed'
ANNOT_RECT_COLOR = '#d0d0d0'
LEGEND_BORDER_WIDTH = 1
LEGEND_ANNOT_X = 1.05
LEGEND_ANNOT_Y = 0.5
MAX_TICKS_PER_AXIS = 5
THRES_FOR_FLIPPED_FACET_TITLES = 10
GRID_WIDTH = 1

VALID_TRACE_TYPES = ['scatter', 'scattergl', 'histogram', 'bar', 'box']

CUSTOM_LABEL_ERROR = (
    "If you are using a dictionary for custom labels for the facet row/col, "
    "make sure each key in that column of the dataframe is in your facet "
    "labels. The keys you need are {}")
示例#28
0
文件: _violin.py 项目: mode/plotly.py
from __future__ import absolute_import

from numbers import Number

from plotly import exceptions, optional_imports
from plotly.figure_factory import utils
from plotly.graph_objs import graph_objs
from plotly.tools import make_subplots

pd = optional_imports.get_module('pandas')
np = optional_imports.get_module('numpy')
scipy_stats = optional_imports.get_module('scipy.stats')


def calc_stats(data):
    """
    Calculate statistics for use in violin plot.
    """
    x = np.asarray(data, np.float)
    vals_min = np.min(x)
    vals_max = np.max(x)
    q2 = np.percentile(x, 50, interpolation='linear')
    q1 = np.percentile(x, 25, interpolation='lower')
    q3 = np.percentile(x, 75, interpolation='higher')
    iqr = q3 - q1
    whisker_dist = 1.5 * iqr

    # in order to prevent drawing whiskers outside the interval
    # of data one defines the whisker positions as:
    d1 = np.min(x[x >= (q1 - whisker_dist)])
    d2 = np.max(x[x <= (q3 + whisker_dist)])
示例#29
0
import subprocess
import sys
import threading
import warnings
from copy import copy

import requests
import retrying
from six import string_types

import plotly
from plotly.basedatatypes import BaseFigure
from plotly.files import PLOTLY_DIR
from plotly.optional_imports import get_module

psutil = get_module('psutil')

# Valid image format constants
# ----------------------------
valid_formats = ('png', 'jpeg', 'webp', 'svg', 'pdf', 'eps')
format_conversions = {fmt: fmt for fmt in valid_formats}
format_conversions.update({'jpg': 'jpeg'})


# Utility functions
# -----------------
def raise_format_value_error(val):
    raise ValueError("""
Invalid value of type {typ} receive as an image format specification.
    Received value: {v}
示例#30
0
from __future__ import absolute_import
import plotly.colors as clrs
from plotly.graph_objs import graph_objs as go
from plotly import exceptions, optional_imports
from plotly import optional_imports
from plotly.graph_objs import graph_objs as go

np = optional_imports.get_module("numpy")
scipy_interp = optional_imports.get_module("scipy.interpolate")

from skimage import measure

# -------------------------- Layout ------------------------------


def _ternary_layout(title="Ternary contour plot",
                    width=550,
                    height=525,
                    pole_labels=["a", "b", "c"]):
    """
    Layout of ternary contour plot, to be passed to ``go.FigureWidget``
    object.

    Parameters
    ==========
    title : str or None
        Title of ternary plot
    width : int
        Figure width.
    height : int
        Figure height.
示例#31
0
# -*- coding: utf-8 -*-

from __future__ import absolute_import

from collections import OrderedDict

from plotly import exceptions, optional_imports
from plotly.graph_objs import graph_objs

# Optional imports, may be None for users that only use our core functionality.
np = optional_imports.get_module('numpy')
scp = optional_imports.get_module('scipy')
sch = optional_imports.get_module('scipy.cluster.hierarchy')
scs = optional_imports.get_module('scipy.spatial')


def create_dendrogram(X,
                      orientation="bottom",
                      labels=None,
                      colorscale=None,
                      distfun=None,
                      linkagefun=lambda x: sch.linkage(x, 'complete'),
                      hovertext=None,
                      color_threshold=None):
    """
    BETA function that returns a dendrogram Plotly figure object.

    :param (ndarray) X: Matrix of observations as array of arrays
    :param (str) orientation: 'top', 'right', 'bottom', or 'left'
    :param (list) labels: List of axis category labels(observation labels)
    :param (list) colorscale: Optional colorscale for dendrogram tree
    def test_get_module_exists_submodule(self):
        import requests.sessions

        module = get_module("requests.sessions")
        self.assertIsNotNone(module)
        self.assertEqual(requests.sessions, module)
示例#33
0
# -*- coding: utf-8 -*-

from __future__ import absolute_import

from collections import OrderedDict

from plotly import exceptions, optional_imports
from plotly.graph_objs import graph_objs

# Optional imports, may be None for users that only use our core functionality.
np = optional_imports.get_module('numpy')
scp = optional_imports.get_module('scipy')
sch = optional_imports.get_module('scipy.cluster.hierarchy')
scs = optional_imports.get_module('scipy.spatial')


def create_dendrogram(X, orientation="bottom", labels=None,
                      colorscale=None, distfun=None,
                      linkagefun=lambda x: sch.linkage(x, 'complete'),
                      hovertext=None):
    """
    BETA function that returns a dendrogram Plotly figure object.

    :param (ndarray) X: Matrix of observations as array of arrays
    :param (str) orientation: 'top', 'right', 'bottom', or 'left'
    :param (list) labels: List of axis category labels(observation labels)
    :param (list) colorscale: Optional colorscale for dendrogram tree
    :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
示例#34
0
文件: utils.py 项目: fu/plotly.py
import re
import sys
import threading
import decimal
from collections import deque

import pytz
from decorator import decorator
from requests.compat import json as _json

from plotly.optional_imports import get_module

from . exceptions import PlotlyError

# Optional imports, may be None for users that only use our core functionality.
numpy = get_module('numpy')
pandas = get_module('pandas')
sage_all = get_module('sage.all')


### incase people are using threading, we lock file reads
lock = threading.Lock()


### general file setup tools ###

def load_json_dict(filename, *args):
    """Checks if file exists. Returns {} if something fails."""
    data = {}
    if os.path.exists(filename):
        lock.acquire()
示例#35
0
from __future__ import absolute_import

from nose.plugins.attrib import attr

from plotly import optional_imports
from plotly.tests.utils import compare_dict, strip_dict_params
from plotly.tests.test_optional.optional_utils import run_fig
from plotly.tests.test_optional.test_matplotlylib.data.lines import *

matplotlylib = optional_imports.get_module('plotly.matplotlylib')

if matplotlylib:
    import matplotlib

    # Force matplotlib to not use any Xwindows backend.
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt


@attr('matplotlib')
def test_simple_line():
    fig, ax = plt.subplots()
    ax.plot(D['x1'], D['y1'], label='simple')
    renderer = run_fig(fig)
    for data_no, data_dict in enumerate(renderer.plotly_fig['data']):
        d1, d2 = strip_dict_params(data_dict, SIMPLE_LINE['data'][data_no], ignore=['uid'])

        equivalent, msg = compare_dict(d1, d2)
        assert equivalent, msg
    equivalent, msg = compare_dict(renderer.plotly_fig['layout'],
                                   SIMPLE_LINE['layout'])
示例#36
0
from __future__ import absolute_import, division

from plotly import exceptions, optional_imports
import plotly.colors as clrs
from plotly.figure_factory import utils
from plotly.graph_objs import graph_objs
from plotly.validators.heatmap import ColorscaleValidator

# Optional imports, may be None for users that only use our core functionality.
np = optional_imports.get_module("numpy")


def validate_annotated_heatmap(z, x, y, annotation_text):
    """
    Annotated-heatmap-specific validations

    Check that if a text matrix is supplied, it has the same
    dimensions as the z matrix.

    See FigureFactory.create_annotated_heatmap() for params

    :raises: (PlotlyError) If z and text matrices do not  have the same
        dimensions.
    """
    if annotation_text is not None and isinstance(annotation_text, list):
        utils.validate_equal_length(z, annotation_text)
        for lst in range(len(z)):
            if len(z[lst]) != len(annotation_text[lst]):
                raise exceptions.PlotlyError("z and text should have the "
                                             "same dimensions")
 def test_get_module_exists(self):
     import math
     module = get_module('math')
     self.assertIsNotNone(module)
     self.assertEqual(math, module)
示例#38
0
from __future__ import absolute_import

from plotly import optional_imports

# Require that numpy exists for figure_factory
np = optional_imports.get_module("numpy")
if np is None:
    raise ImportError("""\
The figure factory module requires the numpy package""")

from plotly.figure_factory._2d_density import create_2d_density
from plotly.figure_factory._annotated_heatmap import create_annotated_heatmap
from plotly.figure_factory._bullet import create_bullet
from plotly.figure_factory._candlestick import create_candlestick
from plotly.figure_factory._dendrogram import create_dendrogram
from plotly.figure_factory._distplot import create_distplot
from plotly.figure_factory._facet_grid import create_facet_grid
from plotly.figure_factory._gantt import create_gantt
from plotly.figure_factory._ohlc import create_ohlc
from plotly.figure_factory._quiver import create_quiver
from plotly.figure_factory._scatterplot import create_scatterplotmatrix
from plotly.figure_factory._streamline import create_streamline
from plotly.figure_factory._table import create_table
from plotly.figure_factory._trisurf import create_trisurf
from plotly.figure_factory._violin import create_violin

if optional_imports.get_module("pandas") is not None:
    from plotly.figure_factory._county_choropleth import create_choropleth
    from plotly.figure_factory._hexbin_mapbox import create_hexbin_mapbox
else:
示例#39
0
from __future__ import absolute_import

import os
import uuid
import warnings
from pkg_resources import resource_string
import time
import webbrowser

from requests.compat import json as _json

import plotly
from plotly import optional_imports, tools, utils
from plotly.exceptions import PlotlyError

ipython = optional_imports.get_module('IPython')
ipython_display = optional_imports.get_module('IPython.display')
matplotlib = optional_imports.get_module('matplotlib')

__PLOTLY_OFFLINE_INITIALIZED = False

__IMAGE_FORMATS = ['jpeg', 'png', 'webp', 'svg']


def download_plotlyjs(download_url):
    warnings.warn('''
        `download_plotlyjs` is deprecated and will be removed in the
        next release. plotly.js is shipped with this module, it is no
        longer necessary to download this bundle separately.
    ''', DeprecationWarning)
    pass
示例#40
0
from __future__ import absolute_import
import base64
import json
import webbrowser
import inspect
import os

import six
from plotly.io import to_json, to_image, write_image, write_html
from plotly import utils, optional_imports
from plotly.io._orca import ensure_server
from plotly.offline.offline import _get_jconfig, get_plotlyjs
from plotly.tools import return_figure_from_figure_or_data

ipython_display = optional_imports.get_module("IPython.display")
IPython = optional_imports.get_module("IPython")

try:
    from http.server import BaseHTTPRequestHandler, HTTPServer
except ImportError:
    # Python 2.7
    from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer


class BaseRenderer(object):
    """
    Base class for all renderers
    """
    def activate(self):
        pass
示例#41
0
from __future__ import absolute_import

from plotly import exceptions, optional_imports
from plotly.figure_factory import utils
from plotly.graph_objs import graph_objs
from plotly.validators.heatmap import ColorscaleValidator

# Optional imports, may be None for users that only use our core functionality.
np = optional_imports.get_module('numpy')


def validate_annotated_heatmap(z, x, y, annotation_text):
    """
    Annotated-heatmap-specific validations

    Check that if a text matrix is supplied, it has the same
    dimensions as the z matrix.

    See FigureFactory.create_annotated_heatmap() for params

    :raises: (PlotlyError) If z and text matrices do not  have the same
        dimensions.
    """
    if annotation_text is not None and isinstance(annotation_text, list):
        utils.validate_equal_length(z, annotation_text)
        for lst in range(len(z)):
            if len(z[lst]) != len(annotation_text[lst]):
                raise exceptions.PlotlyError("z and text should have the "
                                             "same dimensions")

    if x:
示例#42
0
文件: _bullet.py 项目: mode/plotly.py
from __future__ import absolute_import

import collections
import math

from plotly import colors, exceptions, optional_imports
from plotly.figure_factory import utils

import plotly
import plotly.graph_objs as go

pd = optional_imports.get_module('pandas')


def is_sequence(obj):
    return (isinstance(obj, collections.Sequence) and
            not isinstance(obj, str))


def _bullet(df, markers, measures, ranges, subtitles, titles, orientation,
            range_colors, measure_colors, horizontal_spacing,
            vertical_spacing, scatter_options, layout_options):

    num_of_lanes = len(df)
    num_of_rows = num_of_lanes if orientation == 'h' else 1
    num_of_cols = 1 if orientation == 'h' else num_of_lanes
    if not horizontal_spacing:
        horizontal_spacing = 1./num_of_lanes
    if not vertical_spacing:
        vertical_spacing = 1./num_of_lanes
    fig = plotly.tools.make_subplots(
示例#43
0
from __future__ import absolute_import

import os
import uuid
import warnings
from pkg_resources import resource_string
import time
import webbrowser

from requests.compat import json as _json

import plotly
from plotly import optional_imports, tools, utils
from plotly.exceptions import PlotlyError

ipython = optional_imports.get_module('IPython')
ipython_display = optional_imports.get_module('IPython.display')
matplotlib = optional_imports.get_module('matplotlib')

__PLOTLY_OFFLINE_INITIALIZED = False

__IMAGE_FORMATS = ['jpeg', 'png', 'webp', 'svg']


def download_plotlyjs(download_url):
    warnings.warn('''
        `download_plotlyjs` is deprecated and will be removed in the
        next release. plotly.js is shipped with this module, it is no
        longer necessary to download this bundle separately.
    ''', DeprecationWarning)
    pass
示例#44
0
def iplot(figure_or_data, show_link=False, link_text='Export to plot.ly',
          validate=True, image=None, filename='plot_image', image_width=800,
          image_height=600, config=None, auto_play=True, animation_opts=None):
    """
    Draw plotly graphs inside an IPython or Jupyter notebook

    figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or
                      dict or list that describes a Plotly graph.
                      See https://plot.ly/python/ for examples of
                      graph descriptions.

    Keyword arguments:
    show_link (default=False) -- display a link in the bottom-right corner of
                                of the chart that will export the chart to
                                Plotly Cloud or Plotly Enterprise
    link_text (default='Export to plot.ly') -- the text of export link
    validate (default=True) -- validate that all of the keys in the figure
                               are valid? omit if your version of plotly.js
                               has become outdated with your version of
                               graph_reference.json or if you need to include
                               extra, unnecessary keys in your figure.
    image (default=None |'png' |'jpeg' |'svg' |'webp') -- This parameter sets
        the format of the image to be downloaded, if we choose to download an
        image. This parameter has a default value of None indicating that no
        image should be downloaded. Please note: for higher resolution images
        and more export options, consider using plotly.io.write_image. See
        https://plot.ly/python/static-image-export/ for more details.
    filename (default='plot') -- Sets the name of the file your image
        will be saved to. The extension should not be included.
    image_height (default=600) -- Specifies the height of the image in `px`.
    image_width (default=800) -- Specifies the width of the image in `px`.
    config (default=None) -- Plot view options dictionary. Keyword arguments
        `show_link` and `link_text` set the associated options in this
        dictionary if it doesn't contain them already.
    auto_play (default=True) -- Whether to automatically start the animation
        sequence on page load, if the figure contains frames. Has no effect if 
        the figure does not contain frames.
    animation_opts (default=None) -- Dict of custom animation parameters that 
        are used for the automatically started animation on page load. This 
        dict is passed to the function Plotly.animate in Plotly.js. See
        https://github.com/plotly/plotly.js/blob/master/src/plots/animation_attributes.js
        for available options.  Has no effect if the figure
        does not contain frames, or auto_play is False.

    Example:
    ```
    from plotly.offline import init_notebook_mode, iplot
    init_notebook_mode()
    iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}])
    # We can also download an image of the plot by setting the image to the
    format you want. e.g. `image='png'`
    iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}], image='png')
    ```

    animation_opts Example:
    ```
    from plotly.offline import iplot
    figure = {'data': [{'x': [0, 1], 'y': [0, 1]}],
              'layout': {'xaxis': {'range': [0, 5], 'autorange': False},
                         'yaxis': {'range': [0, 5], 'autorange': False},
                         'title': 'Start Title'},
              'frames': [{'data': [{'x': [1, 2], 'y': [1, 2]}]},
                         {'data': [{'x': [1, 4], 'y': [1, 4]}]},
                         {'data': [{'x': [3, 4], 'y': [3, 4]}],
                          'layout': {'title': 'End Title'}}]}
    iplot(figure, animation_opts={'frame': {'duration': 1}})
    ```
    """
    import plotly.io as pio

    ipython = get_module('IPython')
    if not ipython:
        raise ImportError('`iplot` can only run inside an IPython Notebook.')

    config = dict(config) if config else {}
    config.setdefault('showLink', show_link)
    config.setdefault('linkText', link_text)

    # Get figure
    figure = tools.return_figure_from_figure_or_data(figure_or_data, validate)

    # Handle image request
    post_script = build_save_image_post_script(
        image, filename, image_height, image_width, 'iplot')

    # Show figure
    pio.show(figure,
             validate=validate,
             config=config,
             auto_play=auto_play,
             post_script=post_script,
             animation_opts=animation_opts)
示例#45
0
    ColabRenderer,
    JsonRenderer,
    PngRenderer,
    JpegRenderer,
    SvgRenderer,
    PdfRenderer,
    BrowserRenderer,
    IFrameRenderer,
    SphinxGalleryHtmlRenderer,
    SphinxGalleryOrcaRenderer,
    CoCalcRenderer,
    DatabricksRenderer,
)
from plotly.io._utils import validate_coerce_fig_to_dict

ipython = optional_imports.get_module("IPython")
ipython_display = optional_imports.get_module("IPython.display")
nbformat = optional_imports.get_module("nbformat")


# Renderer configuration class
# -----------------------------
class RenderersConfig(object):
    """
    Singleton object containing the current renderer configurations
    """
    def __init__(self):
        self._renderers = {}
        self._default_name = None
        self._default_renderers = []
        self._render_on_display = False
from __future__ import absolute_import
from plotly import optional_imports
from plotly.graph_objs import graph_objs as go

import numpy as np
interpolate = optional_imports.get_module('scipy.interpolate')


def _pl_deep():
    return [[0.0, 'rgb(253, 253, 204)'],
            [0.1, 'rgb(201, 235, 177)'],
            [0.2, 'rgb(145, 216, 163)'],
            [0.3, 'rgb(102, 194, 163)'],
            [0.4, 'rgb(81, 168, 162)'],
            [0.5, 'rgb(72, 141, 157)'],
            [0.6, 'rgb(64, 117, 152)'],
            [0.7, 'rgb(61, 90, 146)'],
            [0.8, 'rgb(65, 64, 123)'],
            [0.9, 'rgb(55, 44, 80)'],
            [1.0, 'rgb(39, 26, 44)']]


def _transform_barycentric_cartesian():
    """
    Returns the transformation matrix from barycentric to cartesian
    coordinates and conversely.
    """
    # reference triangle
    tri_verts = np.array([[0.5, np.sqrt(3) / 2], [0, 0], [1, 0]])
    M = np.array([tri_verts[:, 0], tri_verts[:, 1], np.ones(3)])
    return M, np.linalg.inv(M)
import os
import pandas as pd
import warnings

from math import log, floor
from numbers import Number

from plotly import optional_imports
import plotly.colors as clrs
from plotly.figure_factory import utils
from plotly.exceptions import PlotlyError
import plotly.graph_objs as go

pd.options.mode.chained_assignment = None

shapely = optional_imports.get_module("shapely")
shapefile = optional_imports.get_module("shapefile")
gp = optional_imports.get_module("geopandas")
_plotly_geo = optional_imports.get_module("_plotly_geo")


def _create_us_counties_df(st_to_state_name_dict, state_to_st_dict):

    # URLS
    abs_dir_path = os.path.realpath(_plotly_geo.__file__)

    abs_plotly_geo_path = os.path.dirname(abs_dir_path)

    abs_package_data_dir_path = os.path.join(abs_plotly_geo_path,
                                             "package_data")
示例#48
0
from __future__ import absolute_import

from numbers import Number

from plotly import exceptions, optional_imports
from plotly.figure_factory import utils
from plotly.graph_objs import graph_objs
from plotly.tools import make_subplots

pd = optional_imports.get_module('pandas')
np = optional_imports.get_module('numpy')
scipy_stats = optional_imports.get_module('scipy.stats')


def calc_stats(data):
    """
    Calculate statistics for use in violin plot.
    """
    x = np.asarray(data, np.float)
    vals_min = np.min(x)
    vals_max = np.max(x)
    q2 = np.percentile(x, 50, interpolation='linear')
    q1 = np.percentile(x, 25, interpolation='lower')
    q3 = np.percentile(x, 75, interpolation='higher')
    iqr = q3 - q1
    whisker_dist = 1.5 * iqr

    # in order to prevent drawing whiskers outside the interval
    # of data one defines the whisker positions as:
    d1 = np.min(x[x >= (q1 - whisker_dist)])
    d2 = np.max(x[x <= (q3 + whisker_dist)])
示例#49
0
from __future__ import absolute_import
import plotly.colors as clrs
from plotly.graph_objs import graph_objs as go
from plotly import exceptions, optional_imports
from plotly import optional_imports
from plotly.graph_objs import graph_objs as go

np = optional_imports.get_module("numpy")
sk_measure = optional_imports.get_module("skimage.measure")
scipy_interp = optional_imports.get_module("scipy.interpolate")

# -------------------------- Layout ------------------------------


def _ternary_layout(title="Ternary contour plot",
                    width=550,
                    height=525,
                    pole_labels=["a", "b", "c"]):
    """
    Layout of ternary contour plot, to be passed to ``go.FigureWidget``
    object.

    Parameters
    ==========
    title : str or None
        Title of ternary plot
    width : int
        Figure width.
    height : int
        Figure height.
    pole_labels : str, default ['a', 'b', 'c']
示例#50
0
    def patch_matplotlib():
        # only once
        if PatchedMatplotlib._patched_original_plot is not None:
            return True
        # noinspection PyBroadException
        try:
            # we support matplotlib version 2.0.0 and above
            import matplotlib
            PatchedMatplotlib._matplot_major_version = int(
                matplotlib.__version__.split('.')[0])
            if PatchedMatplotlib._matplot_major_version < 2:
                LoggerRoot.get_base_logger().warning(
                    'matplotlib binding supports version 2.0 and above, found version {}'
                    .format(matplotlib.__version__))
                PatchedMatplotlib._patched_original_plot = False
                return False

            if running_remotely():
                # disable GUI backend - make headless
                matplotlib.rcParams['backend'] = 'agg'
                import matplotlib.pyplot
                matplotlib.pyplot.switch_backend('agg')
            import matplotlib.pyplot as plt
            import matplotlib.figure as figure
            import matplotlib.pylab as plt_pylab
            from matplotlib import _pylab_helpers
            if six.PY2:
                PatchedMatplotlib._patched_original_plot = staticmethod(
                    plt.show)
                PatchedMatplotlib._patched_original_imshow = staticmethod(
                    plt.imshow)
                PatchedMatplotlib._patched_original_figure = staticmethod(
                    figure.Figure.show)
                PatchedMatplotlib._patched_original_savefig = staticmethod(
                    plt.savefig)
                PatchedMatplotlib._patched_original_savefig_plt_pylab = staticmethod(
                    plt_pylab.savefig)
            else:
                PatchedMatplotlib._patched_original_plot = plt.show
                PatchedMatplotlib._patched_original_imshow = plt.imshow
                PatchedMatplotlib._patched_original_figure = figure.Figure.show
                PatchedMatplotlib._patched_original_savefig = plt.savefig
                PatchedMatplotlib._patched_original_savefig_plt_pylab = plt_pylab.savefig

            plt.show = PatchedMatplotlib.patched_show
            figure.Figure.show = PatchedMatplotlib.patched_figure_show
            sys.modules[
                'matplotlib'].pyplot.imshow = PatchedMatplotlib.patched_imshow
            sys.modules[
                'matplotlib'].pyplot.savefig = PatchedMatplotlib.patched_savefig
            sys.modules[
                'matplotlib'].pylab.savefig = PatchedMatplotlib.patched_savefig_pylab
            # patch plotly so we know it failed us.
            from plotly.matplotlylib import renderer
            renderer.warnings = PatchedMatplotlib._PatchWarnings()

            # ignore deprecation warnings from plotly to matplotlib
            try:
                import warnings
                warnings.filterwarnings(
                    action='ignore',
                    category=matplotlib.MatplotlibDeprecationWarning,
                    module='plotly')
            except Exception:
                pass

        except Exception:
            return False

        # patch IPython matplotlib inline mode
        # noinspection PyBroadException
        try:
            if 'IPython' in sys.modules:
                from IPython import get_ipython
                ip = get_ipython()
                if ip and matplotlib.is_interactive():
                    # instead of hooking ipython, we should hook the matplotlib
                    import matplotlib.pyplot as plt
                    PatchedMatplotlib.__patched_original_draw_all = plt.draw_all
                    plt.draw_all = PatchedMatplotlib.__patched_draw_all
                    # ip.events.register('post_execute', PatchedMatplotlib.ipython_post_execute_hook)
        except Exception:
            pass

        # update api version
        from ..backend_api import Session
        PatchedMatplotlib._support_image_plot = Session.check_min_api_version(
            '2.2')

        # create plotly renderer
        try:
            from plotly import optional_imports
            PatchedMatplotlib._matplotlylib = optional_imports.get_module(
                'plotly.matplotlylib')
            PatchedMatplotlib._plotly_renderer = PatchedMatplotlib._matplotlylib.PlotlyRenderer(
            )
        except Exception:
            pass

        return True
示例#51
0
from __future__ import absolute_import
import plotly.colors as clrs
from plotly.graph_objs import graph_objs as go
from plotly import exceptions, optional_imports
from plotly import optional_imports
from plotly.graph_objs import graph_objs as go

np = optional_imports.get_module('numpy')
sk_measure = optional_imports.get_module('skimage.measure')
scipy_interp = optional_imports.get_module('scipy.interpolate')


# -------------------------- Layout ------------------------------


def _ternary_layout(title='Ternary contour plot', width=550, height=525,
                    pole_labels=['a', 'b', 'c']):
    """
    Layout of ternary contour plot, to be passed to ``go.FigureWidget``
    object.

    Parameters
    ==========
    title : str or None
        Title of ternary plot
    width : int
        Figure width.
    height : int
        Figure height.
    pole_labels : str, default ['a', 'b', 'c']
        Names of the three poles of the triangle.