Python plotly.offline() Examples

The following are 13 code examples of plotly.offline(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module plotly , or try the search function .
Example #1
Source File: tools.py    From dash-technical-charting with MIT License 6 votes vote down vote up
def go_offline(connected=False):
    """Take plotting offline.

    __PLOTLY_OFFLINE_INITIALIZED is a secret variable
    in plotly/offline/offline.py.

    Parameters
    ---------
        connected : bool
            Determines if init_notebook_mode should be set to 'connected'.
            99% of time will not need to touch this.

    """
    try:
        pyo.init_notebook_mode(connected)
    except TypeError:
        pyo.init_notebook_mode()

    pyo.__PLOTLY_OFFLINE_INITIALIZED = True 
Example #2
Source File: tools.py    From dash-technical-charting with MIT License 6 votes vote down vote up
def check_url(url=None):
    """Check URL integrity.

    Parameters
    ----------
        url : string
            URL to be checked.

    """
    if url is None:
        if 'http' not in get_config_file()['offline_url']:
            raise Exception("No default offline URL set. "
                            "Please run "
                            "quantmod.set_config_file(offline_url=YOUR_URL) "
                            "to set the default offline URL.")
        else:
            url = get_config_file()['offline_url']

    if url is not None:
        if not isinstance(url, six.string_types):
            raise TypeError("Invalid url '{0}'. "
                            "It should be string."
                            .format(url))

    pyo.download_plotlyjs(url) 
Example #3
Source File: notebook_integration.py    From adaptive with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def ensure_plotly():
    global _plotly_enabled
    try:
        import plotly

        if not _plotly_enabled:
            import plotly.graph_objs
            import plotly.figure_factory
            import plotly.offline

            # This injects javascript and should happen only once
            plotly.offline.init_notebook_mode()
            _plotly_enabled = True
        return plotly
    except ModuleNotFoundError:
        raise RuntimeError("plotly is not installed; plotting is disabled.") 
Example #4
Source File: notebook_integration.py    From adaptive with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def should_update(status):
    try:
        # Get the length of the write buffer size
        buffer_size = len(status.comm.kernel.iopub_thread._events)

        # Make sure to only keep all the messages when the notebook
        # is viewed, this means 'buffer_size == 1'. However, when not
        # viewing the notebook the buffer fills up. When this happens
        # we decide to only add messages to it when a certain probability.
        # i.e. we're offline for 12h, with an update_interval of 0.5s,
        # and without the reduced probability, we have buffer_size=86400.
        # With the correction this is np.log(86400) / np.log(1.1) = 119.2
        return 1.1 ** buffer_size * random.random() < 1
    except Exception:
        # We catch any Exception because we are using a private API.
        return True 
Example #5
Source File: plotly_viewer.py    From pandasgui with MIT License 6 votes vote down vote up
def __init__(self, fig):
        # Create a QApplication instance or use the existing one if it exists
        self.app = QApplication.instance() if QApplication.instance() else QApplication(sys.argv)

        super().__init__()

        # This ensures there is always a reference to this widget and it doesn't get garbage collected
        global instance_list
        instance_list.append(self)

        # self.file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "temp.html"))
        self.file_path = os.path.join(os.getcwd(), 'temp.html')
        self.setWindowTitle("Plotly Viewer")

        plotly.offline.plot(fig, filename=self.file_path, auto_open=False)
        self.load(QUrl.fromLocalFile(self.file_path))

        self.resize(640, 480)
        self.show() 
Example #6
Source File: VisPlotly.py    From NURBS-Python with MIT License 5 votes vote down vote up
def __init__(self, **kwargs):
        super(VisConfig, self).__init__(**kwargs)
        self.dtype = np.float
        # Set Plotly custom variables
        self.figure_image_filename = "temp-figure"
        self.figure_image_format = "png"
        self.figure_filename = "temp-plot.html"

        # Enable online plotting (default is offline plotting as it works perfectly without any issues)
        # @see: https://plot.ly/python/getting-started/#initialization-for-online-plotting
        online_plotting = kwargs.get('online', False)

        # Detect jupyter and/or ipython environment
        try:
            get_ipython
            from plotly.offline import download_plotlyjs, init_notebook_mode
            init_notebook_mode(connected=True)
            self.plotfn = iplot if online_plotting else plotly.offline.iplot
            self.no_ipython = False
        except NameError:
            self.plotfn = plot if online_plotting else plotly.offline.plot
            self.no_ipython = True

        # Get keyword arguments
        self.display_ctrlpts = kwargs.get('ctrlpts', True)
        self.display_evalpts = kwargs.get('evalpts', True)
        self.display_bbox = kwargs.get('bbox', False)
        self.display_trims = kwargs.get('trims', True)
        self.display_legend = kwargs.get('legend', True)
        self.display_axes = kwargs.get('axes', True)
        self.axes_equal = kwargs.get('axes_equal', True)
        self.figure_size = kwargs.get('figure_size', [1024, 768])
        self.trim_size = kwargs.get('trim_size', 1)
        self.line_width = kwargs.get('line_width', 2) 
Example #7
Source File: tools.py    From dash-technical-charting with MIT License 5 votes vote down vote up
def go_online():
    """Take plotting offline."""
    pyo.__PLOTLY_OFFLINE_INITIALIZED = False 
Example #8
Source File: tools.py    From dash-technical-charting with MIT License 5 votes vote down vote up
def is_offline():
    """Check online/offline status."""
    return pyo.__PLOTLY_OFFLINE_INITIALIZED 
Example #9
Source File: plotly_component.py    From cauldron with MIT License 5 votes vote down vote up
def get_version_one_path() -> typing.Optional[str]:
    try:
        from plotly.offline import offline as plotly_offline
    except Exception:
        return None

    return os.path.join(
        environ.paths.clean(os.path.dirname(plotly_offline.__file__)),
        'plotly.min.js'
    ) 
Example #10
Source File: offline.py    From lddmm-ot with MIT License 5 votes vote down vote up
def get_plotlyjs():
    path = os.path.join('offline', 'plotly.min.js')
    plotlyjs = resource_string('plotly', path).decode('utf-8')
    return plotlyjs 
Example #11
Source File: offline.py    From lddmm-ot with MIT License 5 votes vote down vote up
def enable_mpl_offline(resize=False, strip_style=False,
                       verbose=False, show_link=True,
                       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()

    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)) 
Example #12
Source File: showMatLabFig._spatioTemporal.py    From python-urbanPlanning with MIT License 5 votes vote down vote up
def singleBoxplot(array):
    import plotly.express as px
    import pandas as pd
    df=pd.DataFrame(array,columns=["value"])
    fig = px.box(df, y="value",points="all")
    # fig.show() #show in Jupyter
    import plotly
    plotly.offline.plot (fig) #works in spyder

#04-split curve into continuous parts based on the jumping position 使用1维卷积的方法,在曲线跳变点切分曲线 
Example #13
Source File: showMatLabFig._spatioTemporal.py    From python-urbanPlanning with MIT License 4 votes vote down vote up
def graphMerge(num_meanDis_DF):
    plt.clf()
    import plotly.express as px
    from plotly.offline import plot
    
    #01-draw scatter paring
    # coore_columns=["number","mean distance","PHMI"]
    # fig = px.scatter_matrix(num_meanDis_DF[coore_columns],width=1800, height=800)
    # # fig.show() #show in jupyter
    # plot(fig)
     
    #02-draw correlation using plt.matshow-A
    # Corrcoef=np.corrcoef(np.array(num_meanDis_DF[coore_columns]).transpose()) #sns_columns=["number","mean distance","PHMI"]
    # print(Corrcoef)
    # plt.matshow(num_meanDis_DF[coore_columns].corr())
    # plt.xticks(range(len(coore_columns)), coore_columns)
    # plt.yticks(range(len(coore_columns)), coore_columns)
    # plt.colorbar()
    # plt.show()    
    
    #03-draw correlation -B
    # Compute the correlation matrix
    # plt.clf()
    # corr_columns_b=["number","mean distance","PHMI"]
    # corr = num_meanDis_DF[corr_columns_b].corr()    
    corr = num_meanDis_DF.corr()  
    # # Generate a mask for the upper triangle
    # mask = np.triu(np.ones_like(corr, dtype=np.bool))    
    # # Set up the matplotlib figure
    # f, ax = plt.subplots(figsize=(11, 9))    
    # # Generate a custom diverging colormap
    # cmap = sns.diverging_palette(220, 10, as_cmap=True)    
    # # Draw the heatmap with the mask and correct aspect ratio
    # sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,square=True, linewidths=.5, cbar_kws={"shrink": .5})
    
    #04
    # Draw a heatmap with the numeric values in each cell
    plt.clf()
    sns.set()
    f, ax = plt.subplots(figsize=(15, 13))
    sns.heatmap(corr, annot=True, fmt=".2f", linewidths=.5, ax=ax)
        
    #04-draw curves
    # plt.clf()
    # sns_columns=["number","mean distance","PHMI"]
    # sns.set(rc={'figure.figsize':(25,3)})
    # sns.lineplot(data=num_meanDis_DF[sns_columns], palette="tab10", linewidth=2.5)
   
#rpy2调用R编程,参考:https://rpy2.github.io/doc/v2.9.x/html/introduction.html