If this is being run on a headless system the Matplotlib
        backend must be changed to one that doesn't need a display.
558248
def fix_display(self):
        

        try:
            tkinter.Tk()
        except (tkinter.TclError, NameError): # If there is no display.
            try:
                import matplotlib as mpl
            except ImportError:
                pass
            else:
                print("Setting matplotlib backend to Agg")
                mpl.use('Agg')
15326
def plot_or_print(example_farm, example_cluster):
    

    """

    # plot or print power output
    if plt:
        example_cluster.power_output.plot(legend=True, label='example cluster')
        example_farm.power_output.plot(legend=True, label='example farm')
        plt.show()
    else:
        print(example_cluster.power_output)
        print(example_farm.power_output)
1103794
def _set_mpl_backend(self, backend, pylab=False):
        
        import traceback
        from IPython.core.getipython import get_ipython

        generic_error = (
            "\n" + "="*73 + "\n"
            "NOTE: The following error appeared when setting "
            "your Matplotlib backend!!\n" + "="*73 + "\n\n"
            "{0}"
        )

        magic = 'pylab' if pylab else 'matplotlib'

        error = None
        try:
            get_ipython().run_line_magic(magic, backend)
        except RuntimeError as err:
            # This catches errors generated by ipykernel when
            # trying to set a backend. See issue 5541
            if "GUI eventloops" in str(err):
                import matplotlib
                previous_backend = matplotlib.get_backend()
                if not backend in previous_backend.lower():
                    # Only inform about an error if the user selected backend
                    # and the one set by Matplotlib are different. Else this
                    # message is very confusing.
                    error = (
                        "\n"
                        "NOTE: Spyder *can't* set your selected Matplotlib "
                        "backend because there is a previous backend already "
                        "in use.\n\n"
                        "Your backend will be {0}".format(previous_backend)
                    )
                del matplotlib
            # This covers other RuntimeError's
            else:
                error = generic_error.format(traceback.format_exc())
        except Exception:
            error = generic_error.format(traceback.format_exc())

        self._mpl_backend_error = error
842799
def run(self, fig):
        
        # Calling savefig executes the draw() command, putting elements
        # in the correct place.
        fig.savefig(io.BytesIO(), format='png', dpi=fig.dpi)
        if self.close_mpl:
            import matplotlib.pyplot as plt
            plt.close(fig)
        self.crawl_fig(fig)
360727
def single_frame_plot(obj):
    
    obj = Layout.from_values(obj) if isinstance(obj, AdjointLayout) else obj

    backend = Store.current_backend
    renderer = Store.renderers[backend]

    plot_cls = renderer.plotting_class(obj)
    plot = plot_cls(obj, **renderer.plot_options(obj, renderer.size))
    fmt = renderer.params('fig').objects[0] if renderer.fig == 'auto' else renderer.fig
    return plot, renderer, fmt
804074
def display(self, mode='dot'):
        '''
        
        '''

        if  mode == 'neato':
            self.save_dot(self.temp_neo)
            neato_cmd = "%s -o %s %s" % (self.neato, self.temp_dot, self.temp_neo)
            os.system(neato_cmd)
        else:
            self.save_dot(self.temp_dot)

        plot_cmd = "%s %s" % (self.dotty, self.temp_dot)
        os.system(plot_cmd)
1102314
def _distrib_seaborn_(self, label=None, style=None, opts=None):
        
        try:
            kde = False
            rug = True
            if "kde" in opts:
                kde = opts["kde"]
                rug = opts["rug"]
            fig = sns.distplot(self.df[self.x], kde=kde, rug=rug)
            fig = self._set_with_height(fig, opts)
            return fig
        except Exception as e:
            self.err(e, self.distrib_,
                     "Can not draw distribution chart")
105589
def init_matplotlib_backend(backend=None):
    

    import matplotlib

    try:
        os.environ['DISPLAY']
    except KeyError:
        matplotlib.use('Agg')
    else:
        if backend is not None:
            matplotlib.use(backend)
1114287
def seaborn_bar_(self, label=None, style=None, opts=None):
        
        try:
            fig = sns.barplot(self.x, self.y, palette="BuGn_d")
            return fig
        except Exception as e:
            self.err(e, self.seaborn_bar_,
                     "Can not get Seaborn bar chart object")
270330
def untrim(self, n='all'):
        
        if len(self._set_xdata)==0 or len(self._set_ydata)==0:
            self._error("No data. Please use set_data() and plot() prior to zooming.")
            return

        if   _s.fun.is_a_number(n): n = [n]
        elif isinstance(n,str):     n = list(range(len(self._set_xdata)))

        # loop over the specified plots
        for i in n:
            self['xmin'][i] = None
            self['xmax'][i] = None
            self['ymin'][i] = None
            self['ymax'][i] = None
            
        # now show the update.
        self.clear_results()
        if self['autoplot']: self.plot()
        return self
1020876
def _plot_figure(self, idx, fig_format='json'):
        
        self.plot.update(idx)
        if self.embed:
            patch = self.renderer.diff(self.plot, binary=False)
            msg = serialize_json(dict(content=patch.content,
                                      root=self.plot.state._id))
            return msg
1005995
def system_supports_plotting():
    
    try:
        if os.environ['ALLOW_PLOTTING'].lower() == 'true':
            return True
    except KeyError:
        pass
    try:
        p = Popen(["xset", "-q"], stdout=PIPE, stderr=PIPE)
        p.communicate()
        return p.returncode == 0
    except:
        return False
19330
def cleanup(self):
        
        plots = self.traverse(lambda x: x, [BokehPlot])
        for plot in plots:
            if not isinstance(plot, (GenericCompositePlot, GenericElementPlot, GenericOverlayPlot)):
                continue
            streams = list(plot.streams)
            plot.streams = []
            plot._document = None

            if plot.subplots:
                plot.subplots.clear()

            if isinstance(plot, GenericElementPlot):
                for callback in plot.callbacks:
                    streams += callback.streams
                    callback.cleanup()

            for stream in set(streams):
                stream._subscribers = [
                    (p, subscriber) for p, subscriber in stream._subscribers
                    if get_method_owner(subscriber) not in plots
                ]

        if self.comm and self.root is self.handles.get('plot'):
            self.comm.close()
623651
def plotXYCatalog(self, **kwargs):
        
        try:
            from matplotlib import pyplot as pl
        except:
            pl = None

        if pl is not None:
            pl.clf()
            pl.plot(self.xypos[0],self.xypos[1],**kwargs)
1072609
def make_plot(self):
        
        args = self.args

        # constant input causes unhelpful (weird) error messages
        # translate them to English
        inmin = self.timeseries[0].min().value
        if inmin == self.timeseries[0].max().value:
            if not self.got_error:
                self.log(0, 'ERROR: Input has constant values [{:g}]. '
                            'Spectrogram-like products cannot process '
                            'them.'.format(inmin))
            self.got_error = True
        else:
            # create 'raw' spectrogram
            specgram = self.get_spectrogram()

            # there may be data that can't be processed
            if specgram is not None:  # <-DMM: why is this here?
                # apply normalisation
                if args.norm:
                    specgram = specgram.ratio(args.norm)

                self.result = specgram

                # -- update plot defaults

                if not args.ymin:
                    args.ymin = 1/args.secpfft if args.yscale == 'log' else 0

                norm = 'log' if args.color_scale == 'log' else None
                # vmin/vmax set in scale_axes_from_data()
                return specgram.plot(figsize=self.figsize, dpi=self.dpi,
                                     norm=norm, cmap=args.cmap)
172114
def plots_from_files(imspaths, figsize=(10,5), rows=1, titles=None, maintitle=None):
    
    f = plt.figure(figsize=figsize)
    if maintitle is not None: plt.suptitle(maintitle, fontsize=16)
    for i in range(len(imspaths)):
        sp = f.add_subplot(rows, ceildiv(len(imspaths), rows), i+1)
        sp.axis('Off')
        if titles is not None: sp.set_title(titles[i], fontsize=16)
        img = plt.imread(imspaths[i])
        plt.imshow(img)
637128
def headless(self, value):
        
        args = {'--headless'}
        if value is True:
            self._arguments.extend(args)
        else:
            self._arguments = list(set(self._arguments) - args)