Plots images given image files.

    Arguments:
        im_paths (list): list of paths
        figsize (tuple): figure size
        rows (int): number of rows
        titles (list): list of titles
        maintitle (string): main title
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)
48693
def subplots(rows:int, cols:int, imgsize:int=4, figsize:Optional[Tuple[int,int]]=None, title=None, **kwargs):
    ""
    figsize = ifnone(figsize, (imgsize*cols, imgsize*rows))
    fig, axs = plt.subplots(rows,cols,figsize=figsize)
    if rows==cols==1: axs = [[axs]] # subplots(1,1) returns Axes, not [Axes]
    elif (rows==1 and cols!=1) or (cols==1 and rows!=1): axs = [axs]
    if title is not None: fig.suptitle(title, **kwargs)
    return array(axs)
1031423
def plotImagesWithNoise(suite, noise_values, plotPath):
  
  datadir = suite.cfgparser.defaults()["datadir"]

  transform = transforms.Compose([transforms.ToTensor(),
                                  transforms.Normalize((0.1307,), (0.3081,))])
  dataset = datasets.MNIST(datadir, train=False, download=True,
                           transform=transform)

  num_noise = len(noise_values)
  fig = plt.figure(figsize=(num_noise, 4))
  for y in range(4):
    for x in range(num_noise):
      transform.transforms.append(
        RandomNoise(noise_values[x], whiteValue=0.1307 + 2 * 0.3081))
      img, _ = dataset[y]
      transform.transforms.pop()

      ax = fig.add_subplot(4, num_noise, y * num_noise + x + 1)
      ax.set_axis_off()
      ax.imshow(img.numpy().reshape((28, 28)), cmap='gray')
      if y == 0:
        ax.set_title("{0}%".format(noise_values[x] * 100))

  plt.tight_layout()
  plt.savefig(plotPath)
  plt.close()
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)
535144
def save(path, im):
    
    from PIL import Image
    if im.dtype == np.uint8:
        pil_im = Image.fromarray(im)
    else:
        pil_im = Image.fromarray((im*255).astype(np.uint8))
    pil_im.save(path)
1046462
def convert_mat_to_images(args):
    '''
    '''
    dataset = scipy.io.loadmat("{}/{}".format(args.save_path, args.dataset))

    # image pixel data
    X = dataset['X']

    # image class labels (not used in this project)
    Y = dataset['Y']

    total_image = X.shape[0]

    h=args.height
    w=args.width

    for i in range(total_image):
        img = X[i]
        img = np.reshape(img, (28, 28))
        if args.invert:
            img = (1-img)*255
        else:
            img = img*255
        img = Image.fromarray(img, 'L')
        img = img.rotate(-90)
        img = img.resize([h, w], Image.BILINEAR)
        img.save(args.save_path + '/img' + str(i) + '.png')
1285875
def plot_multi(func:Callable[[int,int,plt.Axes],None], r:int=1, c:int=1, figsize:Tuple=(12,6)):
    ""
    axes = plt.subplots(r, c, figsize=figsize)[1]
    for i in range(r):
        for j in range(c): func(i,j,axes[i,j])
1133361
def length_plots(array, name, path, title=None, n50=None, color="#4CB391", figformat="png"):
    """"""
    logging.info("Nanoplotter: Creating length plots for {}.".format(name))
    maxvalx = np.amax(array)
    if n50:
        logging.info("Nanoplotter: Using {} reads with read length N50 of {}bp and maximum of {}bp."
                     .format(array.size, n50, maxvalx))
    else:
        logging.info("Nanoplotter: Using {} reads maximum of {}bp.".format(array.size, maxvalx))

    plots = []
    HistType = namedtuple('HistType', 'weight name ylabel')
    for h_type in [HistType(None, "", "Number of reads"),
                   HistType(array, "Weighted ", "Number of bases")]:
        histogram = Plot(
            path=path + h_type.name.replace(" ", "_") + "Histogram"
            + name.replace(' ', '') + "." + figformat,
            title=h_type.name + "Histogram of read lengths")
        ax = sns.distplot(
            a=array,
            kde=False,
            hist=True,
            bins=max(round(int(maxvalx) / 500), 10),
            color=color,
            hist_kws=dict(weights=h_type.weight,
                          edgecolor=color,
                          linewidth=0.2,
                          alpha=0.8))
        if n50:
            plt.axvline(n50)
            plt.annotate('N50', xy=(n50, np.amax([h.get_height() for h in ax.patches])), size=8)
        ax.set(
            xlabel='Read length',
            ylabel=h_type.ylabel,
            title=title or histogram.title)
        plt.ticklabel_format(style='plain', axis='y')
        histogram.fig = ax.get_figure()
        histogram.save(format=figformat)
        plt.close("all")

        log_histogram = Plot(
            path=path + h_type.name.replace(" ", "_") + "LogTransformed_Histogram"
            + name.replace(' ', '') + "." + figformat,
            title=h_type.name + "Histogram of read lengths after log transformation")
        ax = sns.distplot(
            a=np.log10(array),
            kde=False,
            hist=True,
            color=color,
            hist_kws=dict(weights=h_type.weight,
                          edgecolor=color,
                          linewidth=0.2,
                          alpha=0.8))
        ticks = [10**i for i in range(10) if not 10**i > 10 * maxvalx]
        ax.set(
            xticks=np.log10(ticks),
            xticklabels=ticks,
            xlabel='Read length',
            ylabel=h_type.ylabel,
            title=title or log_histogram.title)
        if n50:
            plt.axvline(np.log10(n50))
            plt.annotate('N50', xy=(np.log10(n50), np.amax(
                [h.get_height() for h in ax.patches])), size=8)
        plt.ticklabel_format(style='plain', axis='y')
        log_histogram.fig = ax.get_figure()
        log_histogram.save(format=figformat)
        plt.close("all")
        plots.extend([histogram, log_histogram])
    plots.append(yield_by_minimal_length_plot(array=array,
                                              name=name,
                                              path=path,
                                              title=title,
                                              color=color,
                                              figformat=figformat))
    return plots
562862
def generate_images(self, pixmaps):
        
        new_images = []

        for image in pixmaps:
            tmp_image = {}
            for img_item in pixmaps[image]:
                if img_item == 'path':
                    path = os.path.join('images',
                                        os.path.basename(
                                            pixmaps[image][img_item]))
                    tmp_image['path'] = fix_path(path)
                    self.images.append(pixmaps[image][img_item])
                else:
                    tmp_image[img_item] = pixmaps[image][img_item]

            new_images.append(tmp_image)

        return new_images
1147298
def show_multi(func:Callable[[int,int],Image], r:int=1, c:int=1, figsize:Tuple=(9,9)):
    ""
    plot_multi(lambda i,j,ax: func(i,j).show(ax), r, c, figsize=figsize)
924127
def subplots(scale_x=None, scale_y=None, scale=None, **kwargs):
  
  '''

  if 'figsize' in kwargs: return plt.subplots(**kwargs)

  width, height = mpl.rcParams['figure.figsize']

  if scale is not None:
    width  *= scale
    height *= scale

  if scale_x is not None:
    width *= scale_x

  if scale_y is not None:
    height *= scale_y

  nrows = kwargs.pop('nrows', 1)
  ncols = kwargs.pop('ncols', 1)

  width  = ncols * width
  height = nrows * height

  return plt.subplots(nrows=nrows, ncols=ncols, figsize=(width,height), **kwargs)
1074965
def save_plots(Figs, filenames, **kwargs):
    
    saved = []
    for key in list(Figs.keys()):
        try:
            plt.figure(num=Figs[key])
            fname = filenames[key]
            if set_env.IS_WIN:  # always truncate filenames if on Windows
                fname = os.path.split(fname)[1]
            if not isServer:  # remove illegal ':' character for windows
                fname = fname.replace(':', '_')
            if 'incl_directory' in kwargs.keys() and not set_env.IS_WIN:
                if kwargs['incl_directory']:
                    pass # do not flatten file name
                else:
                    fname = fname.replace('/', '-') # flatten file name
            else:
                fname = fname.replace('/', '-') # flatten file name
            if 'dpi' in list(kwargs.keys()):
                plt.savefig(fname, dpi=kwargs['dpi'])
            elif isServer:
                plt.savefig(fname, dpi=240)
            else:
                plt.savefig(fname)
            if verbose:
                print(Figs[key], " saved in ", fname)
            saved.append(fname)
            plt.close(Figs[key])
        except Exception as ex:
            print(type(ex), ex)
            print('could not save: ', Figs[key], filenames[key])
            print("output file format not supported ")
    return saved
99722
def plot_figures():
    """"""
    rc("figure", figsize=[8.,4.])
    rc("figure.subplot", left=.08, top=.95, right=.98)
    rc("image", cmap="gray")
    seed(1000)

    Q1 = cp.Gamma(2)
    Q2 = cp.Normal(0, Q1)
    Q = cp.J(Q1, Q2)
    #end

    subplot(121)
    s,t = meshgrid(linspace(0,5,200), linspace(-6,6,200))
    contourf(s,t,Q.pdf([s,t]),50)
    xlabel("$q_1$")
    ylabel("$q_2$")
    subplot(122)
    Qr = Q.sample(500)
    scatter(*Qr, s=10, c="k", marker="s")
    xlabel("$Q_1$")
    ylabel("$Q_2$")
    axis([0,5,-6,6])

    savefig("multivariate.png"); clf()

    Q2 = cp.Gamma(1)
    Q1 = cp.Normal(Q2**2, Q2+1)
    Q = cp.J(Q1, Q2)
    #end

    subplot(121)
    s,t = meshgrid(linspace(-4,7,200), linspace(0,3,200))
    contourf(s,t,Q.pdf([s,t]),30)
    xlabel("$q_1$")
    ylabel("$q_2$")
    subplot(122)
    Qr = Q.sample(500)
    scatter(*Qr)
    xlabel("$Q_1$")
    ylabel("$Q_2$")
    axis([-4,7,0,3])

    savefig("multivariate2.png"); clf()
142900
def load_preprocess_images(image_paths: List[str], image_size: tuple) -> List[np.ndarray]:
    
    image_size = image_size[1:]  # we do not need the number of channels
    images = []
    for image_path in image_paths:
        images.append(load_preprocess_image(image_path, image_size))
    return images
1253110
def display_plots(filebase, directory=None, width=700, height=500, **kwargs):
    """"""
    def show_figure(filebase, directory, **kwargs):
        """Helper function to load in the relevant plot for display."""
        filename = filebase.format(**kwargs)
        if directory is not None:
            filename = directory + '/' + filename
        display(HTML("<img src='{filename}'>".format(filename=filename)))
        
    interact(show_figure, filebase=fixed(filebase), directory=fixed(directory), **kwargs)
1277068
def _draw_title(self):
        
        # This is very laboured. Should be changed when MPL
        # finally has a constraint based layout manager.
        figure = self.figure
        title = self.labels.get('title', '')
        rcParams = self.theme.rcParams
        get_property = self.theme.themeables.property

        # Pick suitable values in inches and convert them to
        # transFigure dimension. This gives fixed spacing
        # margins which work for oblong plots.
        top = figure.subplotpars.top
        W, H = figure.get_size_inches()

        # Adjust the title to avoid overlap with the facet
        # labels on the top row
        # pad/H is inches in transFigure coordinates. A fixed
        # margin value in inches prevents oblong plots from
        # getting unpredictably large spaces.
        try:
            fontsize = get_property('plot_title', 'size')
        except KeyError:
            fontsize = float(rcParams.get('font.size', 12))

        try:
            linespacing = get_property('plot_title', 'linespacing')
        except KeyError:
            linespacing = 1.2

        try:
            margin = get_property('plot_title', 'margin')
        except KeyError:
            pad = 0.09
        else:
            pad = margin.get_as('b', 'in')

        try:
            strip_margin_x = get_property('strip_margin_x')
        except KeyError:
            strip_margin_x = 0

        line_size = fontsize / 72.27
        num_lines = len(title.split('\n'))
        title_size = line_size * linespacing * num_lines
        strip_height = self.facet.strip_size('top')
        # vertical adjustment
        strip_height *= (1 + strip_margin_x)

        x = 0.5
        y = top + (strip_height+title_size/2+pad)/H

        text = figure.text(x, y, title, ha='center', va='center')
        figure._themeable['plot_title'] = text
96238
def plot_lines(it):
    
    data = [go.Scatter(mode='lines', **d) for d in it]
    return py.iplot(data, filename='scatter-mode')