#====================================================================
    plot the fitted results for data fit and refit
    #====================================================================
339802
def fit_plots(ax,xfit,xraw,yfit,yraw):
    '''
    
    '''
    global _yfits_
    _yfits_ = yfit
    ax.plot(xfit, yfit)
    ax.plot(xfit, np.sum(yfit,axis=1))
    ax.scatter(xraw, yraw)
    ax.set_xlabel('Field (log10(mT))')
    ax.set_ylabel('IRM normalization')
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)
1373460
function() {
    this.bar_padding = this.options.bar_padding || 5;
    this.bar_width = this.options.bar_size || this.calculateBarWidth();

    if (this.options.bar_size && !this.options.bar_padding) {
      this.bar_padding = this.graph_width / this.data_size;
    }

    this.options.plot_padding = (this.bar_width / 2) - (this.bar_padding / 2);
    this.step = this.calculateStep();
    this.grid_start_offset = this.bar_padding - 1;
    this.start_y = this.options.height - this.y_padding_bottom;
  }
269721
def plot_figures():
    """"""
    numpy.random.seed(1000)


    def foo(coord, param):
        return param[0] * numpy.e ** (-param[1] * coord)

    coord = numpy.linspace(0, 10, 200)
    distribution = cp.J(cp.Uniform(1, 2), cp.Uniform(0.1, 0.2))

    samples = distribution.sample(50)
    evals = numpy.array([foo(coord, sample) for sample in samples.T])

    plt.plot(coord, evals.T, "k-", lw=3, alpha=0.2)
    plt.xlabel(r"\verb;coord;")
    plt.ylabel(r"function evaluations \verb;foo;")
    plt.savefig("demonstration.png")
    plt.clf()


    samples = distribution.sample(1000, "H")
    evals = [foo(coord, sample) for sample in samples.T]
    expected = numpy.mean(evals, 0)
    deviation = numpy.std(evals, 0)

    plt.fill_between(
        coord, expected-deviation, expected+deviation,
        color="k", alpha=0.3
    )
    plt.plot(coord, expected, "k--", lw=3)
    plt.xlabel(r"\verb;coord;")
    plt.ylabel(r"function evaluations \verb;foo;")
    plt.title("Results using Monte Carlo simulation")
    plt.savefig("results_montecarlo.png")
    plt.clf()


    polynomial_expansion = cp.orth_ttr(8, distribution)
    foo_approx = cp.fit_regression(polynomial_expansion, samples, evals)
    expected = cp.E(foo_approx, distribution)
    deviation = cp.Std(foo_approx, distribution)

    plt.fill_between(
        coord, expected-deviation, expected+deviation,
        color="k", alpha=0.3
    )
    plt.plot(coord, expected, "k--", lw=3)
    plt.xlabel(r"\verb;coord;")
    plt.ylabel(r"function evaluations \verb;foo;")
    plt.title("Results using point collocation method")
    plt.savefig("results_collocation.png")
    plt.clf()


    absissas, weights = cp.generate_quadrature(8, distribution, "C")
    evals = [foo(coord, val) for val in absissas.T]
    foo_approx = cp.fit_quadrature(polynomial_expansion, absissas, weights, evals)
    expected = cp.E(foo_approx, distribution)
    deviation = cp.Std(foo_approx, distribution)

    plt.fill_between(
        coord, expected-deviation, expected+deviation,
        color="k", alpha=0.3
    )
    plt.plot(coord, expected, "k--", lw=3)
    plt.xlabel(r"\verb;coord;")
    plt.ylabel(r"function evaluations \verb;foo;")
    plt.title("Results using psuedo-spectral projection method")
    plt.savefig("results_spectral.png")
    plt.clf()
741962
def plot_fit(self, **kwargs):
        
        import matplotlib.pyplot as plt
        import seaborn as sns

        figsize = kwargs.get('figsize',(10,7))

        if self.latent_variables.estimated is False:
            raise Exception("No latent variables estimated!")
        else:
            plt.figure(figsize=figsize)
            date_index = self.index[max(self.p, self.q):]
            t_params = self.transform_z()
            sigma2, Y, ___ = self._model(self.latent_variables.get_z_values())
            plt.plot(date_index, np.abs(Y-t_params[-1]), label=self.data_name + ' Absolute Demeaned Values')
            plt.plot(date_index, np.power(sigma2,0.5), label='GARCH(' + str(self.p) + ',' + str(self.q) + ') Conditional Volatility',c='black')
            plt.title(self.data_name + " Volatility Plot")  
            plt.legend(loc=2)   
            plt.show()
361428
def plot_data(self):
        
        self.plt.plot(*self.fit.data, **self.options['data'])
35798
def plot_comp(df_var, fig=None, ax=None, **kwargs):
    
    if fig is None and ax is None:
        fig, ax = plt.subplots()
    elif fig is None:
        fig = ax.get_figure()
    elif ax is None:
        ax = fig.gca()
    # plt.clf()
    # plt.cla()
    # ax = sns.regplot(
    #     x='Obs', y='Sim',
    #     data=df_var,
    #     fit_reg=True)

    # add regression expression
    df_var_fit = df_var.dropna(how='any')
    # regr = linear_model.LinearRegression()
    # val_x = df_var_fit['Obs'].values.reshape(-1, 1)
    # val_y = df_var_fit['Sim'].values.reshape(-1, 1)
    # regr.fit(val_x, val_y)
    val_x = df_var_fit['Obs']
    val_y = df_var_fit['Sim']
    slope, intercept, r_value, p_value, std_err = stats.linregress(
        val_x, val_y)
    mae = (val_y - val_x).abs().mean()

    sns.regplot(
        x='Obs', y='Sim',
        data=df_var,
        ax=ax,
        fit_reg=True,
        line_kws={
            'label': "y={0:.2f}x{1}{2:.2f}".format(slope, '+' if intercept>0 else '', intercept) +
            '\n' + '$R^2$={0:.4f}'.format(r_value) +
            '\n' + 'MAE={0:.2f}'.format(mae) +
            '\n' + 'n={}'.format(df_var.shape[0])
        },
        **kwargs
    )
    # ax.plot(val_x, y_pred, color='red', linewidth=2,
    #         label='r2= ' + str("%.3f" % r2) + '\n' +
    #         'y=' + str("%.3f" % a[0][0]) + 'x+' + str("%.2f" % b[0]))

    # ax.legend(fontsize=15)
    ax.legend()
    # ax.set_title(var + '_' + title)

    # set equal plotting range
    x0, x1 = ax.get_xlim()
    y0, y1 = ax.get_ylim()
    lim_low, lim_high = np.min([x0, y0]), np.max([x1, y1])
    ax.set_xlim(lim_low, lim_high)
    ax.set_ylim(lim_low, lim_high)

    # set 1:1 aspect ratio
    ax.set_aspect('equal')

    # add 1:1 line
    ax.plot([lim_low, lim_high], [lim_low, lim_high],
            color='red', linewidth=1, zorder=0)

    # fig = ax.figure

    return fig, ax
1305996
def plot_matched_regions(hits = @hits)
      no_lines = hits.length

      hits_less = hits[0..[no_lines, hits.length - 1].min]

      data = hits_less.each_with_index.map do |hit, i|
        { 'y' => i,
          'start' => hit.hsp_list.map(&:match_query_from).min,
          'stop' => hit.hsp_list.map(&:match_query_to).max,
          'color' => 'black',
          'dotted' => 'true' }
      end .flatten +
             hits_less.each_with_index.map do |hit, i|
               hit.hsp_list.map do |hsp|
                 { 'y' => i,
                   'start' => hsp.match_query_from,
                   'stop' => hsp.match_query_to,
                   'color' => 'orange' }
               end
             end .flatten

      Plot.new(data,
               :lines,
               'Gene Merge Validation: Query coord covered by blast hit' \
               ' (1 line/hit)',
               '',
               'Offset in Prediction',
               'Hit Number',
               hits_less.length)
    end
592007
def plot_series_residuals(self, xres, varied_data, varied_idx, params, **kwargs):
        
        nf = len(self.f_cb(*self.pre_process(xres[0], params)))
        xerr = np.empty((xres.shape[0], nf))
        new_params = np.array(params)

        for idx, row in enumerate(xres):
            new_params[varied_idx] = varied_data[idx]
            xerr[idx, :] = self.f_cb(*self.pre_process(row, params))
        return self.plot_series(xerr, varied_data, varied_idx, **kwargs)
26772
function(){

    var a = this.axes,
        options = this.options,
        series = this.series,
        margin = options.grid.labelMargin,
        T = this._text,
        x = a.x,
        x2 = a.x2,
        y = a.y,
        y2 = a.y2,
        maxOutset = options.grid.outlineWidth,
        i, j, l, dim;

    // TODO post refactor, fix this
    _.each(a, function (axis) {
      axis.calculateTicks();
      axis.calculateTextDimensions(T, options);
    });

    // Title height
    dim = T.dimensions(
      options.title,
      {size: options.fontSize*1.5},
      'font-size:1em;font-weight:bold;',
      'flotr-title'
    );
    this.titleHeight = dim.height;

    // Subtitle height
    dim = T.dimensions(
      options.subtitle,
      {size: options.fontSize},
      'font-size:smaller;',
      'flotr-subtitle'
    );
    this.subtitleHeight = dim.height;

    for(j = 0; j < options.length; ++j){
      if (series[j].points.show){
        maxOutset = Math.max(maxOutset, series[j].points.radius + series[j].points.lineWidth/2);
      }
    }

    var p = this.plotOffset;
    if (x.options.margin === false) {
      p.bottom = 0;
      p.top    = 0;
    } else {
      p.bottom += (options.grid.circular ? 0 : (x.used && x.options.showLabels ?  (x.maxLabel.height + margin) : 0)) +
                  (x.used && x.options.title ? (x.titleSize.height + margin) : 0) + maxOutset;

      p.top    += (options.grid.circular ? 0 : (x2.used && x2.options.showLabels ? (x2.maxLabel.height + margin) : 0)) +
                  (x2.used && x2.options.title ? (x2.titleSize.height + margin) : 0) + this.subtitleHeight + this.titleHeight + maxOutset;
    }
    if (y.options.margin === false) {
      p.left  = 0;
      p.right = 0;
    } else {
      p.left   += (options.grid.circular ? 0 : (y.used && y.options.showLabels ?  (y.maxLabel.width + margin) : 0)) +
                  (y.used && y.options.title ? (y.titleSize.width + margin) : 0) + maxOutset;

      p.right  += (options.grid.circular ? 0 : (y2.used && y2.options.showLabels ? (y2.maxLabel.width + margin) : 0)) +
                  (y2.used && y2.options.title ? (y2.titleSize.width + margin) : 0) + maxOutset;
    }

    p.top = Math.floor(p.top); // In order the outline not to be blured

    this.plotWidth  = this.canvasWidth - p.left - p.right;
    this.plotHeight = this.canvasHeight - p.bottom - p.top;

    // TODO post refactor, fix this
    x.length = x2.length = this.plotWidth;
    y.length = y2.length = this.plotHeight;
    y.offset = y2.offset = this.plotHeight;
    x.setScale();
    x2.setScale();
    y.setScale();
    y2.setScale();
  }
813936
def plotit(self):
        '''
        
        '''
        [self._plot(i) for i in range(len(self.plots))]
325981
def plot(args):
    
    from jcvi.graphics.base import plt, savefig
    from jcvi.graphics.chromosome import ChromosomeMap

    p = OptionParser(plot.__doc__)
    p.add_option("--firstn", type="int", help="Only plot the first N genes")
    p.add_option("--ymax", type="int", help="Y-axis max value")
    p.add_option("--log", action="store_true",
                help="Write plotting data [default: %default]")
    opts, args, iopts = p.set_image_options(args, figsize="6x4")

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

    taggedbed, chr = args
    bed = Bed(taggedbed)
    beds = list(bed.sub_bed(chr))
    old, new = [], []
    i = 0
    for b in beds:
        accn = b.extra[0]
        if "te" in accn:
            continue

        accn, tag = accn.split("|")
        if tag == "OVERLAP":
            continue

        c, r = atg_name(accn)
        if tag == "NEW":
            new.append((i, r))
        else:
            old.append((i, r))
        i += 1

    ngenes = i
    assert ngenes == len(new) + len(old)

    logging.debug("Imported {0} ranks on {1}.".format(ngenes, chr))
    fig = plt.figure(1, (iopts.w, iopts.h))
    root = fig.add_axes([0, 0, 1, 1])

    xstart, xend = .2, .8
    ystart, yend = .2, .8
    pad = .02

    ngenes = opts.firstn or ngenes
    ymax = opts.ymax or 500000

    title = "Assignment of Medtr identifiers"
    if opts.ymax:
        subtitle = "{0}, first {1} genes".format(chr, ngenes)
    else:
        subtitle = "{0}, {1} genes ({2} new)".format(chr, ngenes, len(new))

    chr_map = ChromosomeMap(fig, root, xstart, xend, ystart, yend, pad, 0,
                        ymax, 5, title, subtitle)

    ax = chr_map.axes

    if opts.log:
        from jcvi.utils.table import write_csv
        header = ["x", "y"]
        write_csv(header, new, filename=chr + ".new")
        write_csv(header, old, filename=chr + ".old")

    x, y = zip(*new)
    ax.plot(x, y, "b,")
    x, y = zip(*old)
    ax.plot(x, y, "r,")

    # Legends
    ymid = (ystart + yend) / 2
    y = ymid + pad
    root.plot([.2], [y], "r.", lw=2)
    root.text(.2 + pad, y, "Existing Medtr ids", va="center", size=10)
    y = ymid - pad
    root.plot([.2], [y], "b.", lw=2)
    root.text(.2 + pad, y, "Newly instantiated ids", va="center", size=10)

    ax.set_xlim(0, ngenes)
    ax.set_ylim(0, ymax)
    ax.set_axis_off()

    root.set_xlim(0, 1)
    root.set_ylim(0, 1)
    root.set_axis_off()

    image_name = chr + ".identifiers." + iopts.format
    savefig(image_name, dpi=iopts.dpi, iopts=iopts)
1011809
def match_plot(plotdata, outfile):
    
    fig_h = 2 
    fig_w = 7

    nrows = len(plotdata)
    ncols = 2
    fig = plt.figure(figsize=(fig_w, nrows * fig_h))
    
    for i, (motif, dbmotif, pval) in enumerate(plotdata):
        text = "Motif: %s\nBest match: %s\np-value: %0.2e" % (motif.id, dbmotif.id, pval)
        

        grid = ImageGrid(fig, (nrows, ncols, i * 2 + 1), 
                         nrows_ncols = (2,1),
                         axes_pad=0, 
                         )

        for j in range(2):  
            axes_off(grid[j])

        tmp = NamedTemporaryFile(dir=mytmpdir(), suffix=".png")
        motif.to_img(tmp.name, fmt="PNG", height=6)
        grid[0].imshow(plt.imread(tmp.name), interpolation="none")
        tmp = NamedTemporaryFile(dir=mytmpdir(), suffix=".png")
        dbmotif.to_img(tmp.name, fmt="PNG")
        grid[1].imshow(plt.imread(tmp.name), interpolation="none")

        ax = plt.subplot(nrows, ncols, i * 2 + 2)
        axes_off(ax)

        ax.text(0, 0.5, text,
        horizontalalignment='left',
        verticalalignment='center') 
    
    plt.savefig(outfile, dpi=300, bbox_inches='tight')
    plt.close(fig)
453760
def fitted(self):
        
        return (all(m.fitted for m in self.models.values())
                if self.models else False)
538220
def plot(self):
        ''''''
        import matplotlib.pyplot as plt
        import matplotlib.patches as patches

        # Constants to use throughout drawing
        n = len(self.results)
        nbases = len(self.aligned_reference)
        barheight = 0.4

        # Vary height of figure based on number of results
        figheight = 3 + 3 * (n - 1)
        fig = plt.figure(figsize=(9, figheight))
        ax1 = fig.add_subplot(111)

        # Plot bars to represent coverage area
        # Reference sequence
        ax1.add_patch(patches.Rectangle((0, 0), nbases, barheight,
                                        facecolor='black'))
        # Results
        for i, report in enumerate(self.nonmatches()):
            j = i + 1
            start, stop = report['coverage']
            patch = patches.Rectangle((start, j), stop - start, barheight,
                                      facecolor='darkgray')
            ax1.add_patch(patch)

            # Draw a vertical line for each type of result
            plt.vlines(report['mismatches'], j, j + barheight,
                       colors='b')
            plt.vlines(report['insertions'], j, j + barheight,
                       colors='r')

            # Terminal trailing deletions shouldn't be added
            deletions = []
            crange = range(*report['coverage'])
            deletions = [idx for idx in report['deletions'] if idx in crange]
            plt.vlines(deletions, j, j + barheight,
                       colors='g')

        ax1.set_xlim((0, nbases))
        ax1.set_ylim((-0.3, n + 1))
        ax1.set_yticks([i + barheight / 2 for i in range(n + 1)])
        ax1.set_yticklabels(['Reference'] + self.names)

        # Add legend
        mismatch_patch = patches.Patch(color='blue', label='Mismatch')
        insertion_patch = patches.Patch(color='red', label='Insertion')
        deletion_patch = patches.Patch(color='green', label='Deletion')
        plt.legend(handles=[mismatch_patch, insertion_patch, deletion_patch],
                   loc=1, ncol=3, mode='expand', borderaxespad=0.)

        plt.show()
542179
def fit(self, X, *args, **kwargs):
        

        self.constant_value = self._get_constant_value(X)

        if self.constant_value is None:
            if self.unfittable_model:
                self.model = getattr(scipy.stats, self.model_class)(*args, **kwargs)
            else:
                self.model = getattr(scipy.stats, self.model_class)(X, *args, **kwargs)

            for name in self.METHOD_NAMES:
                attribute = getattr(self.__class__, name)
                if isinstance(attribute, str):
                    setattr(self, name, getattr(self.model, attribute))

                elif attribute is None:
                    setattr(self, name, missing_method_scipy_wrapper(lambda x: x))

        else:
            self._replace_constant_methods()

        self.fitted = True
152998
def save_example_fit(fit):
    
    json_directory = os.path.join('examples', 'json')
    plot_directory = os.path.join('examples', 'plots')
    if not os.path.isdir(json_directory): os.makedirs(json_directory)
    if not os.path.isdir(plot_directory): os.makedirs(plot_directory)

    fit.to_json(os.path.join(json_directory, fit.name + '.json'), meta=fit.metadata)

    plot = Plot(fit)
    plot.save(os.path.join(plot_directory, fit.name + '.svg'))
    plot.close()