Given a dictionary of parameters from pmag.dofisher, pmag.dolnp, or
        pmag.dobingham (meanpars) plots parameters to fig
779601
def plot_eqarea_mean(self, meanpars, fig):
        
        mpars_to_plot = []
        if meanpars == {}:
            return
        if meanpars['calculation_type'] == 'Fisher by polarity':
            for mode in list(meanpars.keys()):
                if type(meanpars[mode]) == dict and meanpars[mode] != {}:
                    mpars_to_plot.append(meanpars[mode])
        else:
            mpars_to_plot.append(meanpars)
        ymin, ymax = fig.get_ylim()
        xmin, xmax = fig.get_xlim()
        if 'color' in meanpars:
            color = meanpars['color']
        else:
            color = 'black'
        size, alpha = 30, 1.
        # put on the mean direction
        for mpars in mpars_to_plot:
            XYM = pmag.dimap(float(mpars["dec"]), float(mpars["inc"]))
            if float(mpars["inc"]) > 0:
                FC = color
                EC = 'black'
            else:
                FC = 'white'
                EC = color
            self.displayed_means.append(fig.scatter([XYM[0]], [
                                        XYM[1]], marker='o', edgecolor=EC, facecolor=FC, s=size, lw=1, clip_on=False, alpha=alpha))

            if "alpha95" in list(mpars.keys()):
                # get the alpha95
                Xcirc, Ycirc = [], []
                Da95, Ia95 = pmag.circ(float(mpars["dec"]), float(
                    mpars["inc"]), float(mpars["alpha95"]))
                for k in range(len(Da95)):
                    XY = pmag.dimap(Da95[k], Ia95[k])
                    Xcirc.append(XY[0])
                    Ycirc.append(XY[1])
                self.displayed_means.append(
                    fig.plot(Xcirc, Ycirc, color, alpha=alpha))

            if self.ie_open:
                self.displayed_means.append(self.ie.scatter([XYM[0]], [
                                            XYM[1]], marker='o', edgecolor=EC, facecolor=FC, s=size, lw=1, clip_on=False, alpha=alpha))
                if "alpha95" in list(mpars.keys()):
                    self.displayed_means.append(
                        self.ie.plot(Xcirc, Ycirc, color, alpha=alpha))
                self.ie.eqarea.set_xlim(xmin, xmax)
                self.ie.eqarea.set_ylim(ymin, ymax)

        fig.set_xlim(xmin, xmax)
        fig.set_ylim(ymin, ymax)
797017
def plot(self, figure_list):
        '''
        
        '''
        # if there is not image data get it from the current plot
        if not self.data == {} and self.data['image_data'] is  None:
            axes = figure_list[0].axes[0]
            if len(axes.images)>0:
                self.data['image_data'] = np.array(axes.images[0].get_array())
                self.data['extent'] = np.array(axes.images[0].get_extent())
                self.plot_settings['cmap'] = axes.images[0].get_cmap().name
                self.plot_settings['xlabel'] = axes.get_xlabel()
                self.plot_settings['ylabel'] = axes.get_ylabel()
                self.plot_settings['title'] = axes.get_title()
                self.plot_settings['interpol'] = axes.images[0].get_interpolation()

        Script.plot(self, figure_list)
57761
def plot_results(fout_png, goea_results, *args, **kws):
    """"""
    if "{NS}" not in fout_png:
        plt_goea_results(fout_png, goea_results, *args, **kws)
    else:
        # Plot separately by NS: BP, MF, CC
        ns2goea_results = cx.defaultdict(list)
        for rec in goea_results:
            ns2goea_results[rec.NS].append(rec)
        for ns_name, ns_res in ns2goea_results.items():
            png = fout_png.format(NS=ns_name)
            plt_goea_results(png, ns_res, *args, **kws)
124255
def make_plots(self, prefix, mcube_map=None, **kwargs):
        """"""

        #mcube_maps = kwargs.pop('mcube_maps', None)
        if mcube_map is None:
            mcube_map = self.model_counts_map()

        plotter = plotting.AnalysisPlotter(self.config['plotting'],
                                           fileio=self.config['fileio'],
                                           logging=self.config['logging'])
        plotter.run(self, mcube_map, prefix=prefix, **kwargs)
260591
def _plot_methods(self):
        """"""
        ret = {}
        for attr in filter(lambda s: not s.startswith("_"), dir(self)):
            obj = getattr(self, attr)
            if isinstance(obj, PlotterInterface):
                ret[attr] = obj._summary
        return ret
77356
def dlogpdf_dtheta(self, f, y, Y_metadata=None):
        
        if self.size > 0:
            if self.not_block_really:
                raise NotImplementedError("Need to make a decorator for this!")
            if isinstance(self.gp_link, link_functions.Identity):
                return self.dlogpdf_link_dtheta(f, y, Y_metadata=Y_metadata)
            else:
                inv_link_f = self.gp_link.transf(f)
                return self.dlogpdf_link_dtheta(inv_link_f, y, Y_metadata=Y_metadata)
        else:
            # There are no parameters so return an empty array for derivatives
            return np.zeros((0, f.shape[0], f.shape[1]))
78532
def plot_gos(fout_png, goids, obo_dag, *args, **kws):
    """"""
    engine = kws['engine'] if 'engine' in kws else 'pydot'
    godagsmall = OboToGoDagSmall(goids=goids, obodag=obo_dag).godag
    godagplot = GODagSmallPlot(godagsmall, *args, **kws)
    godagplot.plt(fout_png, engine)
759457
private void constructMeanStdPreviewsForParam(
            int numEntriesPerPreview, 
            int numParamValues, 
            int paramValue) 
    {
        // calculate mean
        List<double[]> meanParamMeasurements = calculateMeanMeasurementsForParam(
                numEntriesPerPreview, numParamValues, paramValue);
        
        // calculate standard deviation
        List<double[]> stdParamMeasurements = calculateStdMeasurementsForParam(
                numEntriesPerPreview, 
                numParamValues, 
                paramValue,
                meanParamMeasurements);
        
        // get actual measurement names (first four are only additional IDs)
        String[] meanMeasurementNames = 
                this.origMultiRunPreviews.getMeasurementNames();
        meanMeasurementNames = Arrays.copyOfRange(
                meanMeasurementNames, 4, meanMeasurementNames.length);
        
        // Create names for standard deviations.
        // First name is used for indexing and remains unchanged. For the 
        // remaining names, [std] is prepended to the original name.
        String[] stdMeasurementNames = new String[meanMeasurementNames.length];
        stdMeasurementNames[0] = meanMeasurementNames[0];
        for (int m = 1; m < meanMeasurementNames.length; m++) {
            stdMeasurementNames[m] = "[std] " + meanMeasurementNames[m];
        }
        
        // wrap into LearningCurves
        LearningCurve meanLearningCurve = 
                new LearningCurve(meanMeasurementNames[0]);
        meanLearningCurve.setData(
                Arrays.asList(meanMeasurementNames), meanParamMeasurements);
        LearningCurve stdLearningCurve = 
                new LearningCurve(stdMeasurementNames[0]);
        stdLearningCurve.setData(
                Arrays.asList(stdMeasurementNames), stdParamMeasurements);
        
        // wrap into PreviewCollectionLearningCurveWrapper
        Preview meanParamValuePreview = 
                new PreviewCollectionLearningCurveWrapper(
                        meanLearningCurve, 
                        this.origMultiRunPreviews.taskClass);
        Preview stdParamValuePreview = 
                new PreviewCollectionLearningCurveWrapper(
                        stdLearningCurve, 
                        this.origMultiRunPreviews.taskClass);
        
        // store Previews in corresponding PreviewCollections
        this.meanPreviews.setPreview(paramValue, meanParamValuePreview);
        this.stdPreviews.setPreview(paramValue, stdParamValuePreview);
    }
784822
def likelihood2(args):
    
    from matplotlib import gridspec

    p = OptionParser(likelihood2.__doc__)
    opts, args, iopts = p.set_image_options(args, figsize="10x5",
                                style="white", cmap="coolwarm")

    if len(args) != 1:
        sys.exit(not p.print_help())

    jsonfile, = args
    fig = plt.figure(figsize=(iopts.w, iopts.h))
    gs = gridspec.GridSpec(2, 2)
    ax1 = fig.add_subplot(gs[:, 0])
    ax2 = fig.add_subplot(gs[0, 1])
    ax3 = fig.add_subplot(gs[1, 1])
    plt.tight_layout(pad=3)
    pf = plot_panel(jsonfile, ax1, ax2, ax3, opts.cmap)

    root = fig.add_axes([0, 0, 1, 1])
    normalize_axes(root)

    image_name = "likelihood2.{}.".format(pf) + iopts.format
    savefig(image_name, dpi=iopts.dpi, iopts=iopts)
1290630
def plot_d_delta_m(fignum, Bdm, DdeltaM, s):
    
    plt.figure(num=fignum)
    plt.clf()
    if not isServer:
        plt.figtext(.02, .01, version_num)
    start = len(Bdm) - len(DdeltaM)
    plt.plot(Bdm[start:], DdeltaM, 'b')
    plt.xlabel('B (T)')
    plt.ylabel('d (Delta M)/dB')
    plt.title(s)
1198562
def plot_di_sym(fignum, DIblock, sym):
    global globals
    
    X_down, X_up, Y_down, Y_up = [], [], [], []  # initialize some variables
    plt.figure(num=fignum)
#
#   plot the data - separate upper and lower hemispheres
#
    for rec in DIblock:
        Up, Down = 0, 0
        XY = pmag.dimap(rec[0], rec[1])
        if rec[1] >= 0:
            X_down.append(XY[0])
            Y_down.append(XY[1])
        else:
            X_up.append(XY[0])
            Y_up.append(XY[1])
#
    if 'size' not in list(sym.keys()):
        size = 50
    else:
        size = sym['size']
    if 'edgecolor' not in list(sym.keys()):
        sym['edgecolor'] = 'k'
    if len(X_down) > 0:
        plt.scatter(X_down, Y_down, marker=sym['lower'][0],
                    c=sym['lower'][1], s=size, edgecolor=sym['edgecolor'])
        if globals != 0:
            globals.DIlist = X_down
            globals.DIlisty = Y_down
    if len(X_up) > 0:
        plt.scatter(X_up, Y_up, marker=sym['upper'][0],
                    c=sym['upper'][1], s=size, edgecolor=sym['edgecolor'])
        if globals != 0:
            globals.DIlist = X_up
            globals.DIlisty = Y_up
457214
def plot_goid2goobj(fout_png, goid2goobj, *args, **kws):
    """"""
    engine = kws['engine'] if 'engine' in kws else 'pydot'
    godagsmall = OboToGoDagSmall(goid2goobj=goid2goobj).godag
    godagplot = GODagSmallPlot(godagsmall, *args, **kws)
    godagplot.plt(fout_png, engine)
868219
def plotter(molecules, ensemble_lookup, options):
    

    try:
        import matplotlib

        matplotlib.use('Agg')
        import matplotlib.pyplot as plt
    except ImportError:
        print("\n Plotting requires matplotlib to be installed\n")
        sys.exit(1)

    for ensemble in ensemble_lookup.keys():

        # create figure
        fig = plt.figure()

        # create the queries subplot, the left subplot
        # create the left hand subplot
        ax1 = fig.add_subplot(121)

        for query in sorted(ensemble_lookup[ensemble]):
            query_list = []
            query_list.append(query)
            score_structure = classification.make_score_structure(molecules, query_list)
            auc_structure = classification.make_auc_structure(score_structure)
            tpf = []
            fpf = []
            for mol in auc_structure:
                fpf.append(mol[4])
                tpf.append(mol[5])

            # add axis-labels and a title
            ax1.set_xlabel('FPF')
            ax1.set_ylabel('TPF')
            title = 'query performance'
            ax1.set_title(title)

            # add plot data and labels for the legend
            lbl = query
            ax1.plot(fpf, tpf, lw=3, label=lbl)

        # get legend handles and labels, then reverse their order
        handles, labels = ax1.get_legend_handles_labels()
        ax1.legend(handles[::-1], labels[::-1])

        # add the legend
        ax1.legend(handles, labels, loc='best')

        # create the ensemble subplot, the right subplot
        score_structure = classification.make_score_structure(molecules, ensemble_lookup[ensemble])
        auc_structure = classification.make_auc_structure(score_structure)
        tpf = []
        fpf = []
        for mol in auc_structure:
            fpf.append(mol[4])
            tpf.append(mol[5])

        # create right hand subplot
        ax2 = fig.add_subplot(122)

        # add axis-labels and a title
        ax2.set_xlabel('FPF')
        ax2.set_ylabel('TPF')
        title = 'ensemble performance'
        ax2.set_title(title)

        # add plot data and a label for the legend
        lbl = 'ensemble'
        ax2.plot(fpf, tpf, lw=3, label=lbl)

        # get legend handles and labels, then reverse their order
        handles, labels = ax2.get_legend_handles_labels()
        ax2.legend(handles[::-1], labels[::-1])

        # add the legend
        ax2.legend(handles, labels, loc='best')

        # save figure
        figurename = options.outname + '_' + ensemble.replace('.csv', '') + '.pdf'
        filename = os.path.join(os.getcwd(), figurename)
        plt.savefig(filename, bbobx='tight', format='pdf')
1312809
def interact_gridsearch_result_images(show_result_func, cfgdict_list,
                                      cfglbl_list, cfgresult_list,
                                      score_list=None, fnum=None, figtitle='',
                                      unpack=False, max_plots=25, verbose=True,
                                      precision=3, scorelbl='score',
                                      onclick_func=None):
    
    assert callable(show_result_func), 'NEED FUNCTION GOT: %r' % (show_result_func,)

    import utool as ut
    import plottool as pt
    from plottool import plot_helpers as ph
    from plottool import interact_helpers as ih
    if verbose:
        print('Plotting gridsearch results figtitle=%r' % (figtitle,))
    if score_list is None:
        score_list = [None] * len(cfgdict_list)
    else:
        # sort by score if available
        sortx_list = ut.list_argsort(score_list, reverse=True)
        score_list = ut.take(score_list, sortx_list)
        cfgdict_list = ut.take(cfgdict_list, sortx_list)
        cfglbl_list = ut.take(cfglbl_list, sortx_list)
        cfgresult_list = ut.take(cfgresult_list, sortx_list)
    # Dont show too many results only the top few
    score_list = ut.listclip(score_list, max_plots)

    # Show the config results
    fig = pt.figure(fnum=fnum)
    # Get plots for each of the resutls
    nRows, nCols = pt.get_square_row_cols(len(score_list), fix=True)
    next_pnum = pt.make_pnum_nextgen(nRows, nCols)
    for cfgdict, cfglbl, cfgresult, score in zip(cfgdict_list, cfglbl_list,
                                                  cfgresult_list,
                                                  score_list):
        if score is not None:
            cfglbl += '\n' + scorelbl + '=' + ut.repr2(score, precision=precision)
        pnum = next_pnum()
        try:
            if unpack:
                show_result_func(*cfgresult, fnum=fnum, pnum=pnum)
            else:
                show_result_func(cfgresult, fnum=fnum, pnum=pnum)
        except Exception as ex:
            if isinstance(cfgresult, tuple):
                #print(ut.repr4(cfgresult))
                print(ut.depth_profile(cfgresult))
                print(ut.list_type_profile(cfgresult))
            ut.printex(ex, 'error showing', keys=['cfgresult', 'fnum', 'pnum'])
            raise
        #pt.imshow(255 * cfgresult, fnum=fnum, pnum=next_pnum(), title=cfglbl)
        ax = pt.gca()
        pt.set_title(cfglbl, ax=ax)  # , size)
        ph.set_plotdat(ax, 'cfgdict', cfgdict)
        ph.set_plotdat(ax, 'cfglbl', cfglbl)
        ph.set_plotdat(ax, 'cfgresult', cfgresult)
    # Define clicked callback
    def on_clicked(event):
        print('\n[pt] clicked gridsearch axes')
        if event is None or event.xdata is None or event.inaxes is None:
            print('out of axes')
            pass
        else:
            ax = event.inaxes
            plotdat_dict = ph.get_plotdat_dict(ax)
            print(ut.repr4(plotdat_dict))
            cfglbl = ph.get_plotdat(ax, 'cfglbl', None)
            cfgdict = ph.get_plotdat(ax, 'cfgdict', {})
            cfgresult = ph.get_plotdat(ax, 'cfgresult', {})
            infostr_list = [
                ('cfglbl = %s' % (cfglbl,)),
                '',
                ('cfgdict = ' + ut.repr4(cfgdict, sorted_=True)),
            ]
            # Call a user defined function if given
            if onclick_func is not None:
                if unpack:
                    onclick_func(*cfgresult)
                else:
                    onclick_func(cfgresult)
            infostr = ut.msgblock('CLICKED', '\n'.join(infostr_list))
            print(infostr)
    # Connect callbacks
    ih.connect_callback(fig, 'button_press_event', on_clicked)
    pt.set_figtitle(figtitle)
182389
def mp_calc_stats(motifs, fg_fa, bg_fa, bg_name=None):
    """"""
    try:
        stats = calc_stats(motifs, fg_fa, bg_fa, ncpus=1)
    except Exception as e:
        raise
        sys.stderr.write("ERROR: {}\n".format(str(e)))
        stats = {}

    if not bg_name:
        bg_name = "default"

    return bg_name, stats
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)
143570
def do_plot(self, arg):
        
        usable, filename, append = self._redirect_split(arg)
        self.curargs["xscale"] = None
        self.curargs["yscale"] = None
        self._plot_generic(filename)