Example #1
0
def save_figure(
        fig_object: matplotlib.figure.Figure,
        file_path: Text) -> None:
    """Fully saves the figure in pdf and pkl format for later modification.

    This function saves the figure in a pkl and pdf such that later can
        be loaded and easily be modified.
        To have the figure object, one can add the following line of the code
        to the beginning of their code:
            fig_object = plt.figure()

    Args:
        fig_object: Figure object (computed by "plt.figure()")

        file_path: Texting file path without file extension.

    Returns:
        None.

    Raises:
        None.
    """
    # Saves as pdf.
    fig_object.savefig(file_path + '.pdf', dpi=fig_object.dpi)
    # Also saves as pickle.
    with open(file_path + '.pkl', 'wb') as handle:
        pk.dump(fig_object, handle, protocol=pk.HIGHEST_PROTOCOL)
def _save_fig(dst_path: str, figure: matplotlib.figure.Figure) -> None:
    """Save the generated figures for the dataset in dst_dir."""
    # `savefig` do not support GCS, so first save the image locally.
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp_path = os.path.join(tmp_dir, 'tmp.png')
        figure.savefig(tmp_path)
        tf.io.gfile.copy(tmp_path, dst_path, overwrite=FLAGS.overwrite)
    plt.close(figure)
Example #3
0
def fig_to_image(fig: mpl.figure.Figure, **kwargs: dict) -> IO:
    bbox_inches = kwargs.pop("bbox_inches", "tight")
    format_ = "svg"

    img = BytesIO()
    fig.savefig(img, bbox_inches=bbox_inches, format=format_, **kwargs)
    img.seek(0)

    return img
Example #4
0
def svg_from_mpl_axes(fig: mpl.figure.Figure) -> QByteArray:
    """ Convert a matplotlib figure to SVG and store it in a Qt byte array.
    """

    data = io.BytesIO()
    fig.savefig(data, format="svg")
    plt.close(fig)

    return QByteArray(data.getvalue())
Example #5
0
def save_figure(filename: Union[str, IO[bytes]],
                fig: matplotlib.figure.Figure,
                quality: Optional[int] = 90,
                optimize: Optional[bool] = True) -> Tuple[int, int]:
    """Use Agg to save a figure to an image file and return dimensions."""
    canvas = FigureCanvasAgg(fig)
    canvas.draw()
    _, _, width, height = canvas.figure.bbox.bounds
    fig.savefig(filename, quality=quality, optimize=optimize)
    return int(width), int(height)
Example #6
0
def figure_to_base64str(fig: matplotlib.figure.Figure) -> str:
    """Converts a Matplotlib figure to a base64 string encoding.

  Args:
    fig: A matplotlib Figure.

  Returns:
    A base64 encoding of the figure.
  """
    buf = io.BytesIO()
    fig.savefig(buf, bbox_inches='tight', format='png')
    return base64.b64encode(buf.getbuffer().tobytes()).decode('ascii')
Example #7
0
def save_fig(fig: mpl.figure.Figure,
             filename: str,
             directory: Optional[str] = None,
             add_date: bool = False,
             **savefig_kwargs):
    """Saves a Matplotlib figure to disk."""
    if add_date:
        filename = "{}_{}".format(time.strftime("%Y%m%d"), filename)
    savefig_kwargs.setdefault("bbox_inches", "tight")
    savefig_kwargs.setdefault("pad_inches", 0.02)
    save_path = os.path.join(directory, filename)
    fig.savefig(save_path, **savefig_kwargs)
Example #8
0
def savefig(fig: matplotlib.figure.Figure, filename: str) -> None:
    """
    Save a single figure to file.
    
    Arguments
    ---------
    fig : matplotlib.figure.Figure
        Figure to a be saved.
    filename : str
        Name of the file to be written.
    """
    print("saving figure {file}".format(file=filename))
    matplotlib.pyplot.show(block=False)
    fig.savefig(filename, dpi=300)
Example #9
0
def _save_figure(fig: mpl.figure.Figure,
                 path: pathlib.Path,
                 close_figure: bool = False) -> None:
    """Saves a figure at a given location and optionally closes it.

    Args:
        fig (matplotlib.figure.Figure): figure to save
        figure_path (pathlib.Path): path where figure should be saved
        close_figure (bool, optional): whether to close figure after saving, defaults to
            False
    """
    path.parent.mkdir(parents=True, exist_ok=True)
    log.debug(f"saving figure as {path}")
    fig.savefig(path)
    if close_figure:
        plt.close(fig)
Example #10
0
def savefig(f: matplotlib.figure.Figure,
            fpath: str,
            tight: bool = True,
            details: str = None,
            space: float = 0.0,
            **kwargs):
    if tight:
        if details:
            add_parameter_details(f, details, -0.4 + space)
        f.savefig(fpath, bbox_inches='tight', **kwargs)
    else:
        if details:
            f.subplots_adjust(bottom=0.2)
            add_parameter_details(f, details, 0.1)
        f.savefig(fpath, **kwargs)
    if fpath.endswith('png'):
        add_tags_to_png_file(fpath)
    if fpath.endswith('svg'):
        add_tags_to_svg_file(fpath)
Example #11
0
def save_plot_impl(fig: matplotlib.figure.Figure,
                   output_prefix: str, output_name: str,
                   printing_extensions: Sequence[str]) -> List[str]:
    """ Implementation of generic save plot function.

    It loops over all requested file extensions and save the matplotlib fig.

    Args:
        fig: Figure on which the plot was drawn.
        output_prefix: File path to where files should be saved.
        output_name: Filename under which the plot should be saved, but without the file extension.
        printing_extensions: List of file extensions under which plots should be saved. They should
            not contain the dot!
    Returns:
        Filenames under which the plot was saved.
    """
    filenames = []
    for extension in printing_extensions:
        filename = os.path.join(output_prefix, output_name + "." + extension)
        logger.debug(f"Saving matplotlib figure to \"{filename}\"")
        fig.savefig(filename)
        filenames.append(filename)
    return filenames
Example #12
0
def plot_correlations(
    fig: matplotlib.figure.Figure,
    ax: matplotlib.axes.Axes,
    r2: float,
    slope: float,
    y_inter: float,
    corr_vals: np.ndarray,
    vis_vals: np.ndarray,
    scale_factor: Union[float, int],
    corr_bname: str,
    vis_bname: str,
    odir: Union[Path, str],
):
    """
    Plot the correlations between NIR band and the visible bands for
    the Hedley et al. (2005) sunglint correction method

    Parameters
    ----------
    fig : matplotlib.figure object
        Reusing a matplotlib.figure object to avoid the creation many
        fig instantances

    ax : matplotlib.axes._subplots object
        Reusing the axes object

    r2 : float
        The correlation coefficient squared of the linear regression
        between NIR and a VIS band

    slope : float
        The slope/gradient of the linear regression between NIR and
        a VIS band

    y_inter : float
        The intercept of the linear regression between NIR and a
        VIS band

    corr_vals : numpy.ndarray
        1D array containing the NIR values from the ROI

    vis_vals : numpy.ndarray
        1D array containing the VIS values from the ROI

    scale_factor : int or None
        The scale factor used to convert integers to reflectances
        that range [0...1]

    corr_bname : str
        The NIR band number

    vis_bname : str
        The VIS band number

    odir : str
        Directory where the correlation plots are saved

    """
    # clear previous plot
    ax.clear()

    # ----------------------------------- #
    #   Create a unique cmap for hist2d   #
    # ----------------------------------- #
    ncolours = 256

    # get the jet colormap
    colour_array = plt.get_cmap("jet")(range(ncolours))  # 256 x 4

    # change alpha values
    # e.g. low values have alpha = 1, high values have alpha = 0
    # color_array[:,-1] = np.linspace(1.0,0.0,ncolors)
    # e.g. low values have alpha = 0, high values have alpha = 1
    # color_array[:,-1] = np.linspace(0.0,1.0,ncolors)

    # We want only the first few colours to have low alpha
    # as they would represent low density [meshgrid] bins
    # which we are not interested in, and hence would want
    # them to appear as a white colour (alpha ~ 0)
    num_alpha = 25
    colour_array[0:num_alpha, -1] = np.linspace(0.0, 1.0, num_alpha)
    colour_array[num_alpha:, -1] = 1

    # create a colormap object
    cmap = LinearSegmentedColormap.from_list(name="jet_alpha",
                                             colors=colour_array)

    # ----------------------------------- #
    #  Plot density using np.histogram2d  #
    # ----------------------------------- #
    xbin_low, xbin_high = np.percentile(corr_vals, (1, 99),
                                        interpolation="linear")
    ybin_low, ybin_high = np.percentile(vis_vals, (1, 99),
                                        interpolation="linear")

    nbins = [int(xbin_high - xbin_low), int(ybin_high - ybin_low)]

    bin_range = [[int(xbin_low), int(xbin_high)],
                 [int(ybin_low), int(ybin_high)]]

    hist2d, xedges, yedges = np.histogram2d(x=corr_vals,
                                            y=vis_vals,
                                            bins=nbins,
                                            range=bin_range)

    # normalised hist to range [0...1] then rotate and flip
    hist2d = np.flipud(np.rot90(hist2d / hist2d.max()))

    # Mask zeros
    hist_masked = np.ma.masked_where(hist2d == 0, hist2d)

    # use pcolormesh to plot the hist2D
    qm = ax.pcolormesh(xedges, yedges, hist_masked, cmap=cmap)

    # create a colour bar axes within ax
    cbaxes = inset_axes(
        ax,
        width="3%",
        height="30%",
        bbox_to_anchor=(0.37, 0.03, 1, 1),
        loc="lower center",
        bbox_transform=ax.transAxes,
    )

    # Add a colour bar inside the axes
    fig.colorbar(
        cm.ScalarMappable(cmap=cmap),
        cax=cbaxes,
        ticks=[0.0, 1],
        orientation="vertical",
        label="Point Density",
    )

    # ----------------------------------- #
    #     Plot linear regression line     #
    # ----------------------------------- #
    x_range = np.array([xbin_low, xbin_high])
    (ln, ) = ax.plot(
        x_range,
        slope * (x_range) + y_inter,
        color="k",
        linestyle="-",
        label="linear regr.",
    )

    # ----------------------------------- #
    #          Format the figure          #
    # ----------------------------------- #
    # add legend (top left)
    lgnd = ax.legend(loc=2, fontsize=10)

    # add annotation
    ann_str = (r"$r^{2}$" + " = {0:0.2f}\n"
               "slope = {1:0.2f}\n"
               "y-inter = {2:0.2f}".format(r2, slope, y_inter))
    ann = ax.annotate(ann_str,
                      xy=(0.02, 0.76),
                      xycoords="axes fraction",
                      fontsize=10)

    # Add labels to figure
    xlabel = f"Reflectance ({corr_bname})"
    ylabel = f"Reflectance ({vis_bname})"

    if scale_factor is not None:
        if scale_factor > 1:
            xlabel += " " + r"$\times$" + " {0}".format(int(scale_factor))
            ylabel += " " + r"$\times$" + " {0}".format(int(scale_factor))

    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    # plt.show(); sys.exit()

    # Save figure
    png_file = os.path.join(
        odir, "Correlation_{0}_vs_{1}.png".format(corr_bname, vis_bname))

    fig.savefig(png_file,
                format="png",
                bbox_inches="tight",
                pad_inches=0.1,
                dpi=300)

    # delete all lines and annotations from figure,
    # so it can be reused in the next iteration
    qm.remove()
    ln.remove()
    ann.remove()
    lgnd.remove()
Example #13
0
File: Plot.py Project: tttapa/EAGLE
def save(fig: matplotlib.figure.Figure, filename: str):
    fig.savefig(filename)
Example #14
0
def save_figure(fig: matplotlib.figure.Figure, name: str) -> None:
    t_start = time()
    print(f'Saving figure {name}...', end='')
    fig.savefig(name)
    print(f' ({time() - t_start:.2f} s)')
Example #15
0
 def save(cls, fig: mpl.figure.Figure, file_name: str) -> Path:
     file_path = Path.cwd() / cls.directory / f'{file_name}.png'
     fig.savefig(file_path, dpi=fig.dpi)
     return file_path
Example #16
0
def save(figure: matplotlib.figure.Figure, file_name: str) -> None:
    """Save the figure for publication.

    This applies some default export settings.
    """
    figure.savefig(file_name, bbox_inches='tight', pad_inches=0, dpi=600)