def test_get_module_import_exception(self): # Get module that raises an exception on import module_str = "plotly_study.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)
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_study.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), )
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_study.iplot instead of plotly_study.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_study. If you need to trouble shoot, you can do this step manually by NOT running this fuction and entereing the following: =========================================================================== from plotly_study.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_study.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.")
def init_notebook_mode(connected=False): """ Initialize plotly_study.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_study.js to be loaded into the notebook dom. Keyword arguments: connected (default=False) -- If True, the plotly_study.js library will be loaded from an online CDN. If False, the plotly_study.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_study.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_study.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_study.js # library reference is available to the notebook immediately pio.renderers._activate_pending_renderers()
from __future__ import absolute_import from numbers import Number from plotly_study import exceptions, optional_imports import plotly_study.colors as clrs from plotly_study.graph_objs import graph_objs from plotly_study.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)])
# 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 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_study.graph_objs.Figure or plotly_study.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_study.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_study.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_study.animate in plotly_study.js. See https://github.com/plotly/plotly_study.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_study.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_study.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_study.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, )
def test_get_module_exists_submodule(self): import requests.sessions module = get_module("requests.sessions") self.assertIsNotNone(module) self.assertEqual(requests.sessions, module)
from __future__ import absolute_import import base64 import json import webbrowser import inspect import os from os.path import isdir import six from plotly_study.io import to_json, to_image, write_image, write_html from plotly_study import utils, optional_imports from plotly_study.io._orca import ensure_server from plotly_study.offline.offline import _get_jconfig, get_plotlyjs from plotly_study.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):
AzureRenderer, ColabRenderer, JsonRenderer, PngRenderer, JpegRenderer, SvgRenderer, PdfRenderer, BrowserRenderer, IFrameRenderer, SphinxGalleryRenderer, CoCalcRenderer, DatabricksRenderer, ) from plotly_study.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
# -*- coding: utf-8 -*- from __future__ import absolute_import from collections import OrderedDict from plotly_study import exceptions, optional_imports from plotly_study.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'
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_study.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
from __future__ import absolute_import import plotly_study.colors as clrs from plotly_study.graph_objs import graph_objs as go from plotly_study import exceptions, optional_imports from plotly_study import optional_imports from plotly_study.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. pole_labels : str, default ['a', 'b', 'c']
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)
import os import pandas as pd import warnings from math import log, floor from numbers import Number from plotly_study import optional_imports import plotly_study.colors as clrs from plotly_study.figure_factory import utils from plotly_study.exceptions import PlotlyError import plotly_study.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")
from __future__ import absolute_import import six from plotly_study import exceptions, optional_imports import plotly_study.colors as clrs from plotly_study.figure_factory import utils from plotly_study.graph_objs import graph_objs from plotly_study.tools import make_subplots pd = optional_imports.get_module("pandas") DIAG_CHOICES = ["scatter", "histogram", "box"] VALID_COLORMAP_TYPES = ["cat", "seq"] def endpts_to_intervals(endpts): """ Returns a list of intervals for categorical colormaps Accepts a list or tuple of sequentially increasing numbers and returns a list representation of the mathematical intervals with these numbers as endpoints. For example, [1, 6] returns [[-inf, 1], [1, 6], [6, inf]] :raises: (PlotlyError) If input is not a list or tuple :raises: (PlotlyError) If the input contains a string :raises: (PlotlyError) If any number does not increase after the previous one in the sequence """ length = len(endpts) # Check if endpts is a list or tuple
from __future__ import absolute_import, division from plotly_study import exceptions, optional_imports import plotly_study.colors as clrs from plotly_study.figure_factory import utils from plotly_study.graph_objs import graph_objs from plotly_study.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")
from __future__ import absolute_import import datetime import random from unittest import TestCase import pandas as pd from nose.plugins.attrib import attr import plotly_study.tools as tls from plotly_study import optional_imports matplotlylib = optional_imports.get_module("plotly_study.matplotlylib") if matplotlylib: from matplotlib.dates import date2num import matplotlib.pyplot as plt @attr("matplotlib") class TestDateTimes(TestCase): def test_normal_mpl_dates(self): datetime_format = "%Y-%m-%d %H:%M:%S" y = [1, 2, 3, 4] date_strings = [ "2010-01-04 00:00:00", "2010-01-04 10:00:00", "2010-01-04 23:00:59", "2010-01-05 00:00:00", ]
from __future__ import absolute_import from plotly_study 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_study.figure_factory._2d_density import create_2d_density from plotly_study.figure_factory._annotated_heatmap import create_annotated_heatmap from plotly_study.figure_factory._bullet import create_bullet from plotly_study.figure_factory._candlestick import create_candlestick from plotly_study.figure_factory._dendrogram import create_dendrogram from plotly_study.figure_factory._distplot import create_distplot from plotly_study.figure_factory._facet_grid import create_facet_grid from plotly_study.figure_factory._gantt import create_gantt from plotly_study.figure_factory._ohlc import create_ohlc from plotly_study.figure_factory._quiver import create_quiver from plotly_study.figure_factory._scatterplot import create_scatterplotmatrix from plotly_study.figure_factory._streamline import create_streamline from plotly_study.figure_factory._table import create_table from plotly_study.figure_factory._trisurf import create_trisurf from plotly_study.figure_factory._violin import create_violin if optional_imports.get_module("pandas") is not None: from plotly_study.figure_factory._county_choropleth import create_choropleth