Draw/animate and show and/or save a autofig plot
183914
def _show_or_save(self, save, show, animate,
                      draw_sidebars=True,
                      draw_title=True,
                      tight_layout=False,
                      subplot_grid=None,
                      **kwargs):
        
        if animate and not show and not save:
            logger.warning("setting show to True since animate=True and save not provided")
            show = True

        if animate:
            # prefer times over time
            times = kwargs.get('times', kwargs.get('time', None))
            save_kwargs = kwargs.get('save_kwargs', {})

            if times is None:
                # then let's try to get all SYNTHETIC times
                # it would be nice to only do ENABLED, but then we have to worry about compute
                # it would also be nice to worry about models... but then you should filter first
                logger.info("no times were providing, so defaulting to animate over all dataset times")
                times = []
                for dataset in self.datasets:
                    ps = self.filter(dataset=dataset, context='model')
                    if len(ps.times):
                        # for the case of meshes/spectra
                        times += [float(t) for t in ps.times]
                    else:
                        for param in ps.filter(qualifier='times').to_list():
                            times += list(param.get_value())

                times = sorted(list(set(times)))

            logger.info("calling autofig.animate(i={}, draw_sidebars={}, draw_title={}, tight_layout={}, save={}, show={}, save_kwargs={})".format(times, draw_sidebars, draw_title, tight_layout, save, show, save_kwargs))

            mplanim = self.gcf().animate(i=times,
                                         draw_sidebars=draw_sidebars,
                                         draw_title=draw_title,
                                         tight_layout=tight_layout,
                                         subplot_grid=subplot_grid,
                                         save=save,
                                         show=show,
                                         save_kwargs=save_kwargs)

            afig = self.gcf()

            # clear the autofig figure
            self.clf()

            return afig, mplanim

        else:
            time = kwargs.get('time', None)

            if isinstance(time, str):
                time = self.get_value(time, context=['component', 'system'])

            logger.info("calling autofig.draw(i={}, draw_sidebars={}, draw_title={}, tight_layout={}, save={}, show={})".format(time, draw_sidebars, draw_title, tight_layout, save, show))
            fig = self.gcf().draw(i=time,
                                  draw_sidebars=draw_sidebars,
                                  draw_title=draw_title,
                                  tight_layout=tight_layout,
                                  subplot_grid=subplot_grid,
                                  save=save, show=show)
            # clear the figure so next call will start over and future shows will work
            afig = self.gcf()
            self.clf()

            return afig, fig
435868
def plot_init(fignum, w, h):
    
    global fig_x_pos, fig_y_pos, plt_num
    dpi = 80
    if isServer:
        dpi = 240
    # plt.ion()
    plt_num += 1
    fig = plt.figure(num=fignum, figsize=(w, h), dpi=dpi)
    if (not isServer) and (not set_env.IS_NOTEBOOK):
        plt.get_current_fig_manager().show()
        # plt.get_current_fig_manager().window.wm_geometry('+%d+%d' %
        # (fig_x_pos,fig_y_pos)) # this only works with matplotlib.use('TKAgg')
        fig_x_pos = fig_x_pos + dpi * (w) + 25
        if plt_num == 3:
            plt_num = 0
            fig_x_pos = 25
            fig_y_pos = fig_y_pos + dpi * (h) + 25
        plt.figtext(.02, .01, version_num)
# plt.connect('button_press_event',click)
#
    # plt.ioff()
    return fig
488779
def plot_and_save(self,
                      data,
                      w=800,
                      h=420,
                      filename='chart',
                      overwrite=True):
        """"""
        self.save(data, filename, overwrite)
        return IFrame(filename + '.html', w, h)
443326
def save_graph(cn_topo, filename, showintfs=False, showaddrs=False):
    '''
     
    '''
    __do_draw(cn_topo, showintfs=showintfs, showaddrs=showaddrs)
    pyp.savefig(filename)
1010045
def plot(self):
        

        # if we're disabled or have no data columns, clear everything!
        if not self.button_enabled.is_checked() or len(self) == 0:
            self._set_number_of_plots(0)
            return self

        # if there is no script, create a default
        if not self.combo_autoscript.get_index()==0:
            self.script.set_text(self._autoscript())

        ##### Try the script and make the curves / plots match

        try:
            # get globals for sin, cos etc
            g = _n.__dict__
            g.update(dict(d=self))
            g.update(dict(xlabels='x', ylabels='y'))

            # run the script.
            exec(self.script.get_text(), g)

            # x & y should now be data arrays, lists of data arrays or Nones
            x = g['x']
            y = g['y']

            # make it the right shape
            if x == None: x = [None]
            if y == None: y = [None]
            if not _spinmob.fun.is_iterable(x[0]) and not x[0] == None: x = [x]
            if not _spinmob.fun.is_iterable(y[0]) and not y[0] == None: y = [y]
            if len(x) == 1 and not len(y) == 1: x = x*len(y)
            if len(y) == 1 and not len(x) == 1: y = y*len(x)


            # xlabels and ylabels should be strings or lists of strings
            xlabels = g['xlabels']
            ylabels = g['ylabels']

            # make sure we have exactly the right number of plots
            self._set_number_of_plots(len(x))
            self._update_linked_axes()

            # return if there is nothing.
            if len(x) == 0: return

            # now plot everything
            for n in range(max(len(x),len(y))-1,-1,-1):

                # Create data for "None" cases.
                if x[n] is None: x[n] = list(range(len(y[n])))
                if y[n] is None: y[n] = list(range(len(x[n])))
                self._curves[n].setData(x[n],y[n])

                # get the labels for the curves

                # if it's a string, use the same label for all axes
                if type(xlabels) in [str,type(None)]: xlabel = xlabels
                elif n < len(xlabels):                xlabel = xlabels[n]
                else:                                 xlabel = ''

                if type(ylabels) in [str,type(None)]: ylabel = ylabels
                elif n < len(ylabels):                ylabel = ylabels[n]
                else:                                 ylabel = ''

                # set the labels
                i = min(n, len(self.plot_widgets)-1)
                self.plot_widgets[i].setLabel('left',   ylabel)
                self.plot_widgets[i].setLabel('bottom', xlabel)

                # special case: hide if None
                if xlabel == None: self.plot_widgets[i].getAxis('bottom').showLabel(False)
                if ylabel == None: self.plot_widgets[i].getAxis('left')  .showLabel(False)

            # unpink the script, since it seems to have worked
            self.script.set_colors('black','white')

        # otherwise, look angry and don't autosave
        except: self.script.set_colors('black','pink')

        return self
403488
def save_anim(self, fig, animate, init, bitrate=10000, fps=30):
        """"""
        from matplotlib import animation
        anim = animation.FuncAnimation(fig, animate, init_func=init, frames=360, interval=20)
        FFMpegWriter = animation.writers['ffmpeg']
        writer = FFMpegWriter(bitrate= bitrate, fps=fps)
        # Save #
        self.avi_path = self.base_dir + self.short_name + '.avi'
        anim.save(self.avi_path, writer=writer, codec='x264')
1211529
public void drawAnimation(Animation anim, float x, float y, Color col) {
		predraw();
		anim.draw(x, y, col);
		currentColor.bind();
		postdraw();
	}
1178334
def plot_interactive(mergepkl, noisepkl=None, thresh=6.0, thresh_link=7.0, ignoret=None, savehtml=True, url_path='plots'):
    

    data = readdata(mergepkl)
    circleinds = calcinds(data, thresh, ignoret)
    crossinds = calcinds(data, -1*thresh, ignoret)
    edgeinds = calcinds(data, thresh_link, ignoret)

    workdir = os.path.dirname(mergepkl)
    fileroot = os.path.basename(mergepkl).rstrip('_merge.pkl').lstrip('cands_')

    logger.info('Total on target time: {} s'.format(calcontime(data, inds=circleinds+crossinds+edgeinds)))

    if noisepkl:
        noiseplot = plotnoisecum(noisepkl)
    else:
        noiseplot = None

    combined = plotall(data, circleinds=circleinds, crossinds=crossinds, edgeinds=edgeinds,
                       htmlname=None, noiseplot=noiseplot, url_path=url_path, fileroot=fileroot)

    if savehtml:
        output_file(mergepkl.rstrip('.pkl') + '.html')
        save(combined)
    else:
        return combined
72896
def add_plot(x, y, xl, yl, fig, ax, LATEX=False, linestyle=None, **kwargs):
    """"""
    if LATEX:
        xl_data = xl[1]  # NOQA
        yl_data = yl[1]
    else:
        xl_data = xl[0]  # NOQA
        yl_data = yl[0]

    for idx in range(len(y)):
        ax.plot(x, y[idx], label=yl_data[idx], linestyle=linestyle)

    ax.legend(loc='upper right')
    ax.set_ylim(auto=True)
282889
function () {
		var axis = this,
			chart = axis.chart,
			pointer = chart.pointer;

		// hide tooltip and hover states
		if (pointer.reset) {
			pointer.reset(true);
		}

		// render the axis
		axis.render();

		// move plot lines and bands
		each(axis.plotLinesAndBands, function (plotLine) {
			plotLine.render();
		});

		// mark associated series as dirty and ready for redraw
		each(axis.series, function (series) {
			series.isDirty = true;
		});

	}
1045869
def do_plot(args):
    
    import ugali.utils.plotting
    import pylab as plt

    config,name,label,coord = args
    filenames = make_filenames(config,label)
    srcfile = filenames['srcfile']
    samfile = filenames['samfile']
    memfile = filenames['memfile']

    if not exists(srcfile):
        logger.warning("Couldn't find %s; skipping..."%srcfile)
        return
    if not exists(samfile):
        logger.warning("Couldn't find %s; skipping..."%samfile)
        return

    config = ugali.utils.config.Config(config)
    burn = config['mcmc']['nburn']*config['mcmc']['nwalkers']

    source = ugali.analysis.source.Source()
    source.load(srcfile,section='source')

    outfile = samfile.replace('.npy','.png')
    ugali.utils.plotting.plotTriangle(srcfile,samfile,burn=burn)
    logger.info("  Writing %s..."%outfile)
    plt.savefig(outfile,bbox_inches='tight',dpi=60)
    plt.close()

    plotter = ugali.utils.plotting.SourcePlotter(source,config,radius=0.5)

    data = fitsio.read(memfile,trim_strings=True) if exists(memfile) else None
    if data is not None:
        plt.figure()
        kernel,isochrone = source.kernel,source.isochrone
        ugali.utils.plotting.plotMembership(config,data,kernel,isochrone)
        outfile = samfile.replace('.npy','_mem.png')
        logger.info("  Writing %s..."%outfile)
        plt.savefig(outfile,bbox_inches='tight',dpi=60)
        plt.close()
            
        plotter.plot6(data)

        outfile = samfile.replace('.npy','_6panel.png')
        logger.info("  Writing %s..."%outfile)
        plt.savefig(outfile,bbox_inches='tight',dpi=60)

        outfile = samfile.replace('.npy','_6panel.pdf')
        logger.info("  Writing %s..."%outfile)
        plt.savefig(outfile,bbox_inches='tight',dpi=60)

        plt.close()

    try:
        title = name
        plotter.plot4()
        outfile = samfile.replace('.npy','_4panel.png')
        logger.info("  Writing %s..."%outfile)
        plt.suptitle(title)
        plt.savefig(outfile,bbox_inches='tight',dpi=60)
        plt.close()
    except:
        logger.warning("  Failed to create plotter.plot4()")
188007
function(adj, canvas, animating) {
      var f = adj.getData('type'),
          ctxObj = this.edge.CanvasStyles;
      if(f != 'none') {
        var width = adj.getData('lineWidth'),
            color = adj.getData('color'),
            ctx = canvas.getCtx();
        
        ctx.lineWidth = width;
        ctx.fillStyle = ctx.strokeStyle = color;
        
        for(var s in ctxObj) {
          ctx[s] = adj.getCanvasStyle(s);
        }

        this.edgeTypes[f].call(this, adj, canvas, animating);
      }
    }
1278545
def display_animation(anim, **kwargs):
    """"""
    from IPython.display import HTML
    return HTML(anim_to_html(anim, **kwargs))
923007
def save_plot(axes="gca", path=None):
    

    global line_attributes

    # choose a path to save to
    if path==None: path = _s.dialogs.Save("*.plot", default_directory="save_plot_default_directory")

    if path=="":
        print("aborted.")
        return

    if not path.split(".")[-1] == "plot": path = path+".plot"

    f = file(path, "w")

    # if no argument was given, get the current axes
    if axes=="gca": axes=_pylab.gca()

    # now loop over the available lines
    f.write("title="  +axes.title.get_text().replace('\n', '\\n')+'\n')
    f.write("xlabel="+axes.xaxis.label.get_text().replace('\n','\\n')+'\n')
    f.write("ylabel="+axes.yaxis.label.get_text().replace('\n','\\n')+'\n')

    for l in axes.lines:
        # write the data header
        f.write("trace=new\n")
        f.write("legend="+l.get_label().replace('\n', '\\n')+"\n")

        for a in line_attributes: f.write(a+"="+str(_pylab.getp(l, a)).replace('\n','')+"\n")

        # get the data
        x = l.get_xdata()
        y = l.get_ydata()

        # loop over the data
        for n in range(0, len(x)): f.write(str(float(x[n])) + " " + str(float(y[n])) + "\n")

    f.close()
1267497
def main():
    
    fmt,plot='svg',0
    if '-h' in sys.argv: # check if help is needed
        print(main.__doc__)
        sys.exit() # graceful quit
    elif '-f' in sys.argv: # ask for filename
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        f=open(file,'r')
        input=f.readlines()
    Data=[]
    for line in input:
        line.replace('\n','')
        if '\t' in line:   # read in the data from standard input
            rec=line.split('\t') # split each line on space to get records
        else:
            rec=line.split() # split each line on space to get records
        Data.append(float(rec[0]))
    
#
    if len(Data) >=10: 
        QQ={'unf1':1}
        pmagplotlib.plot_init(QQ['unf1'],5,5)
        pmagplotlib.plot_qq_unf(QQ['unf1'],Data,'QQ-Uniform') # make plot
    else:
        print('you need N> 10')
        sys.exit()
    pmagplotlib.draw_figs(QQ) 
    files={}
    for key in list(QQ.keys()):
        files[key]=key+'.'+fmt 
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        titles={}
        titles['eq']='Equal Area Plot'
        EQ = pmagplotlib.add_borders(EQ,titles,black,purple)
        pmagplotlib.save_plots(QQ,files)
    elif plot==1:
        files['qq']=file+'.'+fmt 
        pmagplotlib.save_plots(QQ,files)
    else:
        ans=input(" S[a]ve to save plot, [q]uit without saving:  ")
        if ans=="a": pmagplotlib.save_plots(QQ,files)
757679
function(node, opt, animating) {
       var that = this, 
       viz = this.viz, 
       canvas = viz.canvas,
       config = this.config,
       ctx = canvas.getCtx();
       var nodeAlpha = node.getData('alpha');
       node.eachSubnode(function(elem) {
         if(opt.plotSubtree(node, elem) && elem.exist && elem.drawn) {
             var adj = node.getAdjacency(elem.id);
             !animating && opt.onBeforePlotLine(adj);
             ctx.globalAlpha = Math.min(nodeAlpha, elem.getData('alpha'));
             that.plotLine(adj, canvas, animating);
             !animating && opt.onAfterPlotLine(adj);
             that.plotTree(elem, opt, animating);
         }
       });
       if(node.drawn) {
           !animating && opt.onBeforePlotNode(node);
           this.plotNode(node, canvas, animating);
           !animating && opt.onAfterPlotNode(node);
           if(!opt.hideLabels && opt.withLabels && nodeAlpha >= 0.95) 
               this.labels.plotLabel(canvas, node, opt);
           else 
               this.labels.hideLabel(node, false);
       } else {
           this.labels.hideLabel(node, true);
       }
   }
712464
def _save_plot(self, *args, extension='pdf', **kwargs):
        
        import matplotlib.pyplot as plt

        tmp_path = make_temp_dir()
        filename = '{}.{}'.format(str(uuid.uuid4()), extension.strip('.'))
        filepath = posixpath.join(tmp_path, filename)

        plt.savefig(filepath, *args, **kwargs)
        return filepath