How to use the abipy.tools.plotting.get_ax_fig_plt function in abipy

To help you get started, we’ve selected a few abipy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github abinit / abipy / abipy / boltztrap / boltztrap.py View on Github external
def plot_dos(self,ax=None,erange=None,fontsize=8,legend=True,**kwargs):
        """
        Plot dos for the results in the Robot
        """
        ax1, fig, plt = get_ax_fig_plt(ax=ax)
        self.plot_dos_ax(ax1,erange=erange,legend=legend,fontsize=fontsize,**kwargs)
        return fig
github abinit / abipy / abipy / dfpt / phonons.py View on Github external
Args:
            ax: matplotlib :class:`Axes` or None if a new figure should be created.
            stacked: True if DOS partial contributions should be stacked on top of each other.
            units: Units for phonon plots. Possible values in ("eV", "meV", "Ha", "cm-1", "Thz"). Case-insensitive.
            colormap: Have a look at the colormaps
                `here `_
                and decide which one you'd like:
            alpha: The alpha blending value, between 0 (transparent) and 1 (opaque)

        Returns:
            matplotlib figure.
        """
        lw = kwargs.pop("lw", 2)
        factor = _factor_ev2units(units)

        ax, fig, plt = get_ax_fig_plt(ax)
        cmap = plt.get_cmap(colormap)

        ax.grid(True)
        set_axlims(ax, kwargs.pop("xlim", None), "x")
        set_axlims(ax, kwargs.pop("ylim", None), "y")
        ax.set_xlabel('Frequency %s' % _unit_tag(units))
        ax.set_ylabel('PJDOS %s' % _dos_label_from_units(units))

        # Type projected DOSes.
        num_plots = len(self.pjdos_type_dict)
        cumulative = np.zeros(len(self.wmesh))

        for i, (symbol, pjdos) in enumerate(self.pjdos_type_dict.items()):
            x, y = pjdos.mesh * factor, pjdos.values / factor
            color = cmap(float(i) / (num_plots - 1))
            if not stacked:
github abinit / abipy / abipy / dfpt / phonons.py View on Github external
marker: String defining the marker to plot. Syntax `markername:fact` where fact is a float used
                to scale the marker size.
            width: String defining the width to plot. Syntax `widthname:fact` where fact is a float used
                to scale the stripe size.
            match_bands: if True the bands will be matched based on the scalar product between the eigenvectors.

        Returns:
            `matplotlib` figure.
        """
        # Select the band range.
        if branch_range is None:
            branch_range = range(self.num_branches)
        else:
            branch_range = range(branch_range[0], branch_range[1], 1)

        ax, fig, plt = get_ax_fig_plt(ax)

        # Decorate the axis (e.g add ticks and labels).
        self.decorate_ax(ax, units=units, qlabels=qlabels)

        if "color" not in kwargs:
            kwargs["color"] = "black"

        if "linewidth" not in kwargs:
            kwargs["linewidth"] = 2.0

        # Plot the phonon branches.
        self.plot_ax(ax, branch_range, units=units, match_bands=match_bands, **kwargs)

        # Add markers to the plot.
        if marker is not None:
            try:
github abinit / abipy / abipy / electrons / bse.py View on Github external
"""
        Plot all the components of the tensor.

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.

        ==============  ==============================================================
        kwargs          Meaning
        ==============  ==============================================================
        red_coords      True to plot the reduced coordinate tensor (Default: True)
        ==============  ==============================================================

        Returns: |matplotlib-Figure|
        """
        red_coords = kwargs.pop("red_coords", True)
        ax, fig, plt = get_ax_fig_plt(ax=ax)
        ax.grid(True)
        ax.set_xlabel('Frequency (eV)')
        ax.set_ylabel('Dielectric tensor')

        #if not kwargs:
        #    kwargs = {"color": "black", "linewidth": 2.0}

        # Plot the 6 independent components
        for icomponent in [0, 4, 8, 1, 2, 5]:
            self.plot_ax(ax, icomponent, red_coords, *args, **kwargs)

        return fig
github abinit / abipy / abipy / electrons / ebands.py View on Github external
Plot the the DOSes on the same figure.
        Use `gridplot` to plot DOSes on different figures.

        Args:
            ax: matplotlib :class:`Axes` or None if a new figure should be created.
            e0: Option used to define the zero of energy in the band structure plot. Possible values:
                - `fermie`: shift all eigenvalues to have zero energy at the Fermi energy (`self.fermie`).
                -  Number e.g e0=0.5: shift all eigenvalues to have zero energy at 0.5 eV
                -  None: Don't shift energies, equivalent to e0=0
            xlims: Set the data limits for the x-axis. Accept tuple e.g. `(left, right)`
                   or scalar e.g. `left`. If left (right) is None, default values are used

        Returns:
            `matplotlib` figure.
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)

        can_use_basename = self._can_use_basenames_as_labels()

        for label, dos in self.edoses_dict.items():
            if can_use_basename:
                label = os.path.basename(label)
            else:
                # Use relative paths if label is a file.
                if os.path.isfile(label): label = os.path.relpath(label)
            dos.plot_ax(ax, e0, label=label)

        ax.grid(True)
        ax.set_xlabel("Energy [eV]")
        ax.set_ylabel('DOS [states/eV]')
        set_axlims(ax, xlims, "x")
        ax.legend(loc="best")
github abinit / abipy / abipy / electrons / psps.py View on Github external
def plot_ffspl(self, ax=None, ecut_ffnl=None, ders=(0,), with_qn=0, with_fact=False, **kwargs):
        """
        Plot the nonlocal part of the pseudopotential in q-space.

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.
            ecut_ffnl: Max cutoff energy for ffnl plot (optional)
            ders: Tuple used to select the derivatives to be plotted.
            with_qn:

        Returns: |matplotlib-Figure|
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)

        color = kwargs.pop("color", "black")
        linewidth = kwargs.pop("linewidth", 2.0)

        color_l = {-1: "black", 0: "red", 1: "blue", 2: "green", 3: "orange"}
        linestyles_n = ["solid", '-', '--', '-.', ":"]
        scale = None
        l_seen = set()

        qmesh, vlspl = self.reader.read_vlspl()

        all_projs = self.reader.read_projectors()
        for itypat, projs_type in enumerate(all_projs):
            # Loop over the projectors for this atom type.
            for p in projs_type:
                for der, values in enumerate(p.data):
github abinit / abipy / abipy / electrons / optic.py View on Github external
components: List of cartesian tensor components to plot e.g. ["xx", "xy"].
                "all" if all components available on file should be plotted on the same ax.
            what: quantity to plot. "re" for real part, "im" for imaginary. Accepts also "abs", "angle".
            itemp: Temperature index.
            ax: |matplotlib-Axes| or None if a new figure should be created.
            xlims: Set the data limits for the x-axis. Accept tuple e.g. ``(left, right)``
                   or scalar e.g. ``left``. If left (right) is None, default values are used.
            with_xlabel: True if x-label should be added.
            label: True to add legend label to each curve.
            fontsize: Legend and label fontsize.

        Returns: |matplotlib-Figure|
        """
        comp2eps = self.reader.read_lineps(components, itemp=itemp)

        ax, fig, plt = get_ax_fig_plt(ax=ax)
        for comp, eps in comp2eps.items():
            values = LINEPS_WHAT2EFUNC[what](eps)
            # Note: I'm skipping the first point at w=0 because optic does not compute it!
            # The same trick is used in the other plots.
            ax.plot(self.wmesh[1:], values[1:],
                    label=self.get_linopt_latex_label(what, comp) if label is None else label)

        ax.grid(True)
        if with_xlabel: ax.set_xlabel('Photon Energy (eV)')
        set_axlims(ax, xlims, "x")
        ax.legend(loc="best", fontsize=fontsize, shadow=True)

        return fig
github abinit / abipy / abipy / dfpt / gruneisen.py View on Github external
or scalar e.g. ``left``. If left (right) is None, default values are used
            match_bands: if True tries to follow the band along the path based on the scalar product of the eigenvectors.
            qlabels: dictionary whose keys are tuples with the reduced coordinates of the q-points.
                The values are the labels. e.g. ``qlabels = {(0.0,0.0,0.0): "$\Gamma$", (0.5,0,0): "L"}``.
            branch_range: Tuple specifying the minimum and maximum branch index to plot (default: all branches are plotted).

        Returns: |matplotlib-Figure|.
        """
        if not self.phbands_qpath_vol: return None
        phbands = self.phbands_qpath_vol[self.iv0]
        factor = phbands.phfactor_ev2units(units)
        gamma_fact *= factor

        # Build axes (ax_bands and ax_doses)
        if with_doses is None:
            ax_bands, fig, plt = get_ax_fig_plt(ax=None)
        else:
            import matplotlib.pyplot as plt
            from matplotlib.gridspec import GridSpec
            dos_names = list(_ALL_DOS_NAMES.keys()) if with_doses == "all" else list_strings(with_doses)
            ncols = 1 + len(dos_names)
            fig = plt.figure()
            width_ratios = [2] + len(dos_names) * [0.2]
            gspec = GridSpec(1, ncols, width_ratios=width_ratios, wspace=0.05)
            ax_bands = plt.subplot(gspec[0])
            ax_doses = []
            for i in range(len(dos_names)):
                ax_doses.append(plt.subplot(gspec[i + 1], sharey=ax_bands))

        # Plot phonon bands.
        phbands.plot(ax=ax_bands, units=units, match_bands=match_bands, show=False, qlabels=qlabels,
                     branch_range=branch_range)
github abinit / abipy / abipy / electrons / bse.py View on Github external
ax: |matplotlib-Axes| or None if a new figure should be created.
            mdf_type:
            cplx_mode: string defining the data to print (case-insensitive).
                Possible choices are `re` for the real part, `im` for imaginary part only. `abs` for the absolute value.
            qpoint: index of the q-point or :class:`Kpoint` object or None to plot emacro_avg.
            xlims: Set the data limits for the y-axis. Accept tuple e.g. `(left, right)`
                  or scalar e.g. `left`. If left (right) is None, default values are used
            ylims: Same meaning as `ylims` but for the y-axis
            with_legend: True if legend should be added
            with_xlabel:
            with_ylabel:
            fontsize: Legend and label fontsize.

        Return: |matplotlib-Figure|
        """
        ax, fig, plt = get_ax_fig_plt(ax=ax)
        ax.grid(True)

        if with_xlabel: ax.set_xlabel("Frequency (eV)")
        if with_ylabel: ax.set_ylabel(self.MDF_TYPECPLX2TEX[mdf_type][cplx_mode.lower()])

        can_use_basename = self._can_use_basenames_as_labels()
        qtag = "avg" if qpoint is None else repr(qpoint)

        lines, legends = [], []
        for label, mdf_dict in self._mdfs.items():
            mdf = mdf_dict[mdf_type]
            # Plot the average value
            l = mdf.plot_ax(ax, qpoint, cplx_mode=cplx_mode, **kwargs)[0]
            lines.append(l)
            if can_use_basename:
                label = os.path.basename(label)
github abinit / abipy / abipy / dynamics / hist.py View on Github external
def plot_energies(self, ax=None, fontsize=8, **kwargs):
        """
        Plot the total energies as function of the iteration step.

        Args:
            ax: |matplotlib-Axes| or None if a new figure should be created.
            fontsize: Legend and title fontsize.

        Returns: |matplotlib-Figure|
        """
        # TODO max force and pressure
        ax, fig, plt = get_ax_fig_plt(ax=ax)

        terms = self.reader.read_eterms()
        for key, values in terms.items():
            if np.all(values == 0.0): continue
            ax.plot(self.steps, values, marker="o", label=key)

        ax.set_xlabel('Step')
        ax.set_ylabel('Energies (eV)')
        ax.grid(True)
        ax.legend(loc='best', fontsize=fontsize, shadow=True)

        return fig