--- title: Static Plots keywords: fastai sidebar: home_sidebar summary: "All types of plots in matplotlib are included in this module. This includes bands,DOS and other general plots, which can be saved as pdf,png,jpg and other formats that matplotlib offers." description: "All types of plots in matplotlib are included in this module. This includes bands,DOS and other general plots, which can be saved as pdf,png,jpg and other formats that matplotlib offers." nb_path: "StaticPlots.ipynb" ---
{% raw %}
{% endraw %} {% raw %}

  Index 
  XmlElementTree 
  StaticPlots● 
  InteractivePlots 
  Utilities 
  StructureIO 
  Widgets 
  MainAPI 

{% endraw %}

Passing Large Number of Arguments as a Dictionary

  • Let's take example of _plot_bands. It requires 10 arguments and most of them are default, but in order to tweak parameters, you still need to access them. Follow These steps to input arguments easily.
  • In code cell, write _plot_bands? and hit enter. This will give Signature and DocString.
  • Copy arguments and pass to a dictionary dict(what you copied). In a Jupyter Notebook cell, you can edit it:
{% raw %}
arg_dict=dict(
    ax=None,
    kpath=None,
    bands=None,
    showlegend=True,
    E_Fermi=0,
    color=(1, 0, 0.8),
    ls='solid',
    lw=0.7,
    )
arg_dict
{'ax': None,
 'kpath': None,
 'bands': None,
 'showlegend': True,
 'E_Fermi': 0,
 'color': (1, 0, 0.8),
 'ls': 'solid',
 'lw': 0.7}
{% endraw %} {% raw %}
{% endraw %}
  • As you can see, I deleted few unnecessary arguments. Now you can use dictionary unpacking operator ** inside function, it will pass all arguments present in dictionary. Make sure you do not change name of variables, although you can delete as few of them.
  • Usage: Call function as _plot_bands(**arg_dict). You can edit dictionary on fly, or can save it to a file to read (Not recommended, could be a threat to your system security as reading dictionaries from a file could run potentially harmful commands as well.)

Customize Matplotlib's Figure

{% raw %}

modify_axes[source]

modify_axes(ax=None, xticks=[], xt_labels=[], xlim=[], yticks=[], yt_labels=[], ylim=[], xlabel=None, ylabel=None, vlines=True, zeroline=True)

  • Returns None, applies given settings on axes. Prefered to use before other plotting.
  • Parameters
    • ax : Matplotlib axes object.
    • (x,y)ticks : List of positions on (x,y axes).
    • (xt,yt)_labels : List of labels on (x,y) ticks points.
    • (x,y)lim : [min, max] of (x,y) axes.
    • (x,y)label : axes labels.
    • vlines : If true, drawn when ylim is not empty.
    • zeroline : If True, drawn when xlim is not empty.
{% endraw %} {% raw %}
{% endraw %} {% raw %}

get_axes[source]

get_axes(figsize=(3.4, 2.6), nrows=1, ncols=1, widths=[], heights=[], axes_off=[], axes_3d=[], sharex=False, sharey=False, azim=45, elev=15, ortho3d=True, **subplots_adjust_kwargs)

  • Returns flatten axes of initialized figure, based on plt.subplots(). If you want to access parent figure, use ax.get_figure() or current figure as plt.gcf().
  • Parameters
    • figsize : Tuple (width, height). Default is (3.4,2.6).
    • nrows : Default 1.
    • ncols : Default 1.
    • widths : List with len(widths)==nrows, to set width ratios of subplots.
    • heights : List with len(heights)==ncols, to set height ratios of subplots.
    • share(x,y): Share axes between plots, this removes shared ticks automatically.
    • axes_off : Turn off axes visibility, If nrows = ncols = 1, set True/False, If anyone of nrows or ncols > 1, provide list of axes indices to turn off. If both nrows and ncols > 1, provide list of tuples (x_index,y_index) of axes.
    • axes_3d : Change axes to 3D. If nrows = ncols = 1, set True/False, If anyone of nrows or ncols > 1, provide list of axes indices to turn off. If both nrows and ncols > 1, provide list of tuples (x_index,y_index) of axes. azim,elev : Matplotlib's 3D angles, defualt are 45,15. ortho3d : Only works for 3D axes. If True, x,y,z are orthogonal, otherwise perspective.
    • **subplots_adjust_kwargs : These are same as plt.subplots_adjust()'s arguements.
{% endraw %} {% raw %}

append_axes[source]

append_axes(ax, position='right', size=0.2, pad=0.1, sharex=False, sharey=False, **kwargs)

Append an axes to the given ax at given position |top|right|left|bottom|. Useful for adding custom colorbar. kwargs are passed to mpl_toolkits.axes_grid1.make_axes_locatable.append_axes. Returns appended axes.

{% endraw %} {% raw %}
{% endraw %}

Tweaking get_axes by using gridspec.

  • This is a powerful way yo include any type of grid. For this, first use gs = axs[0,0].get_gridspec() and then remove axes you want to replace for another shape, then add required axis by plt.gcf().add_subplot(gs[x_ind, y_ind]). This process is illustrated in below examples.
  • Examples
    • Axes remain same, just widths and height ratios are chnaged.
{% raw %}
import pivotpy.s_plots as sp 
axs = get_axes(figsize=(3.4,2.6),ncols=3,widths=[3.4,1,3.4],nrows=3,heights=[2.6,1,2.6],wspace=0.076,hspace=0.1)
[sp.modify_axes(ax=ax,xticks=[0],yticks=[0]) for ax in axs.ravel()]
[sp.add_colorbar(ax=ax,ticks=[]) for ax in [axs[1,0],axs[1,2]]];
_ = [sp.add_colorbar(ax=ax,vertical=True,ticks=[]) for ax in [axs[0,1],axs[2,1]]]
_ = append_axes(axs[0,2],sharey=True,sharex=True)
2022-04-24T13:54:53.068503 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/
{% endraw %}
  • Here we will remove and regenerate axes based on our grid choice.
{% raw %}
axs=get_axes(figsize=(5,3.4),nrows=3,ncols=2,widths=[1,1],heights=[1,7,7],wspace=0.4,hspace=0.4,axes_off=[(2,0)],sharex=True,sharey=True)
import pivotpy.s_plots as sp 
import matplotlib.pyplot as plt
gs = axs[0,0].get_gridspec()
axs_to_remove=[*axs[0, :],*axs[1:, 1]]
for ax in axs_to_remove:
    ax.remove()
axlarge = plt.gcf().add_subplot(gs[0, :])
axv = plt.gcf().add_subplot(gs[1:, 1])
sp.modify_axes(ax=axv)
sp.add_colorbar(ax=axv,cax=axlarge,vertical=False)
sp.add_text(ax=axs[1,0],txts='axis[1,0]',xs=0.25,ys=0.5)
sp.add_text(ax=axs[2,0],txts='axis[2,0] is off',xs=0.15,ys=0.5)
import pivotpy.vr_parser as vp 
vr=vp.export_vasprun(path='E:/Research/graphene_example/ISPIN_1/bands/vasprun.xml')
sp.splot_bands(path_evr=vr,ax=axv,txt='Plotting',E_Fermi=-3,ktick_inds=[0,15,30],ktick_vals=['A','B','C'])
sp.add_text(ax=axv,txts='BigAxes',xs=0.25,ys=0.5)
modify_axes(axv,vlines=True,ylim=[-5,5])
Loading from PowerShell Exported Data...
2022-04-24T13:54:53.537249 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/
{% endraw %}
  • A minial example below shows deleting an axes and then adding a 3D axes with same dimensions.
{% raw %}
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt 
import pivotpy as pp 
ax = get_axes(nrows=2,ncols=2,widths=[1,2],heights=[1,2],axes_3d=[(1,1)])
2022-04-24T13:54:53.912251 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/
{% endraw %}

Broken Axes Plots

Sometimes we need to display different ranges of data scattered far apart. Use fubction break_spines defined below and see an example.

{% raw %}

break_spines[source]

break_spines(ax, spines, symbol='╱', **kwargs)

Simulates broken axes using subplots. Need to fix heights according to given data for real aspect. Also plot the same data on each axes and set axes limits.

  • Parameters
    • ax : Axes who's spine(s) to edit.
    • spines: str,list, str/list of any of ['top','bottom','left','right'].
    • symbol: Defult is u'╱'. Its at 60 degrees. so you can apply rotation to make it any angle. kwargs are passed to plt.text.
{% endraw %} {% raw %}
{% endraw %} {% raw %}
import numpy as np 
import matplotlib.pyplot as plt
x = np.linspace(0,30,50)
y = x**2*np.abs(np.cos(x))
a1, a2 = get_axes(nrows=2)
a1.plot(x,y)
a2.plot(x,y)
# Set limits of data same as height_ratios to make visual correct
a2.set_ylim([0,100])
a1.set_ylim([400,800])
plt.subplots_adjust(hspace=0.12)
break_spines(a1,'bottom','~',rotation=35)
break_spines(a2,['top'],'~',rotation=35)
_ = a1.set_title('$f(x) = x^2|\cos(x)|$')
2022-04-24T13:54:54.350039 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/
{% endraw %}

Simple Band Struture Plots

{% raw %}
{% endraw %}

Working in object-oriented way, we can have plenty of options in matplotlib. See the example below, which provides an overview of flexibility of matplotlib. All functions are defined in object-oriented way for better compatibility and flexibility.

Example: Graphene

{% raw %}
import pivotpy.vr_parser as vp
vr1=vp.export_vasprun(path=f1)
vr2=vp.export_vasprun(path=f2)
import pivotpy.s_plots as sp
import matplotlib.pyplot as plt

ax = sp.get_axes(ncols=3,figsize=(10.2,2.6),sharey=True)
ax0=_plot_bands(ax=ax[0],kpath=vr2.kpath,bands=vr2.bands,color='k',color_='c',lw_ = 0.7,ls_='dashed',showlegend=True)

ax1=_plot_bands(ax=ax[1],kpath=vr1.kpath,bands=vr1.bands,color='y')

ax2=_plot_bands(ax=ax[2],kpath=vr1.kpath,bands=vr1.bands,color='y')
ax2=_plot_bands(ax=ax[2],kpath=vr2.kpath,bands=vr2.bands,showlegend=True,color='r',color_ = 'g',lw_ = 0.5, ls_ = 'dashed')
xticks=[vr1.kpath[i] for i in [0,30,60,-1]]
txts=["Polarized","Unpolarized","Comparison"]
for axes,txt in zip(ax,txts):
    if axes==ax0:
        sp.modify_axes(ax=axes,ylabel='Energy (eV)')
    modify_axes(ax=axes,ylim=[-10,10],xlim=[xticks[0],xticks[-1]],xticks=xticks,xt_labels=[r'$\Gamma$','M','K',r'$\Gamma$'])
    axes.text(0.05,0.9,txt,bbox=dict(edgecolor='white',facecolor='white', alpha=0.9),transform=axes.transAxes,color='red')
plt.subplots_adjust(hspace=0.01,wspace=0.05)
Loading from PowerShell Exported Data...
2022-04-24T13:54:54.912896 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/
{% endraw %} {% raw %}

add_text[source]

add_text(ax=None, xs=0.25, ys=0.9, txts='[List]', colors='r', transform=True, **kwargs)

  • Adds text entries on axes, given single string or list.
  • Parameters
    • xs : List of x coordinates relative to axes or single coordinate.
    • ys : List of y coordinates relative to axes or single coordinate.
    • txts : List of strings or one string.
    • colors: List of x colors of txts or one color.
    • transform: Dafault is True and positions are relative to axes, If False, positions are in data coordinates.

kwargs are passed to plt.text.

{% endraw %} {% raw %}
{% endraw %} {% raw %}

splot_bands[source]

splot_bands(path_evr=None, ax=None, skipk=None, kseg_inds=[], elim=[], ktick_inds=[], ktick_vals=[], E_Fermi=None, txt=None, xytxt=[0.2, 0.9], ctxt='black', interp_nk={}, **kwargs)

  • Returns axes object and plot on which all matplotlib allowed actions could be performed.
  • Parameters
    • path_evr : path/to/vasprun.xml or output of export_vasprun. Auto picks in CWD.
    • ax : Matplotlib axes object, if not given, one is created.
    • skipk : Number of kpoints to skip, default will be from IBZKPT.
    • kseg_inds : Points where kpath is broken.
    • elim : [min,max] of energy range.
    • E_Fermi : If not given, automatically picked from export_vasprun.
    • ktick_inds : High symmetry kpoints indices.abs
    • ktick_vals : High Symmetry kpoints labels.
    • txt,xytxt and ctxt are extra arguments for text on figure.
    • interp_nk : Dictionary with keys 'n' and 'k' for interpolation.

Additional kwargs are passed to matplotlib.lines.Lin2D. For passing a keyword to spindown channel, append an underscore, e.g 'lw' goes to SpinUp and 'lw_' goes to SpinDown.

  • Returns
    • ax : matplotlib axes object with plotted bands.
{% endraw %} {% raw %}
{% endraw %}

Below is example where you can add multiple text entries on a splot_bands.

{% raw %}
import pivotpy.s_plots as sp
ax=splot_bands(path_evr=f2,elim=[-5,5],ktick_inds=[0,30,60,-1],ktick_vals=['W','K','',''],txt='Graphene',ctxt='r',color='r',color_='k',lw_=0.5,label='Up',label_ = 'Down')
add_text(ax=ax,xs=[0.35,0.5],ys=[0.55,0.7],txts=[r'$E_{gap}$ = 0 eV','edge states'],colors=['red','blue'],fontsize=15)
2022-04-24T13:54:55.287897 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/
{% endraw %} {% raw %}

add_legend[source]

add_legend(ax=None, colors=[], labels=[], styles='solid', widths=0.7, anchor=(0, 1), ncol=3, loc='lower left', fontsize='small', frameon=False, **kwargs)

  • Adds custom legeneds on a given axes,returns None.
  • Parameters
    • ax : Matplotlib axes.
    • colors : List of colors.
    • labels : List of labels.
    • styles : str or list of line styles.
    • widths : str or list of line widths.

kwargs are passed to plt.legend. Given arguments like anchor,ncol etc are preferred.

{% endraw %} {% raw %}
{% endraw %} {% raw %}

add_colorbar[source]

add_colorbar(ax, cax=None, cmap_or_clist=None, N=256, ticks=[0.16666666666666666, 0.5, 0.8333333333333334], ticklabels=['r', 'g', 'b'], tickloc='right', vertical=True, fontsize=8)

  • Plots colorbar on a given axes. This axes should be only for colorbar. Returns None or throws ValueError for given colors.
  • Parameters

    • ax : Matplotlib axes for which colorbar will be added.
    • cax : Matplotlib axes for colorbar. If not given, one is created.
    • cmap_or_clist: List/array of colors in or colormap's name. If None(default), first tries to get latest splot_rgb_lines colormap
                and if no success, then `RGB_f` colorbar is added. If nothing works, matplotlib's default colormap is plotted.
    • N : int, number of color points Default 256.
    • ticks : List of tick values to show on colorbar in interval [0,1].
    • ticklabels : List of labels for ticks.
    • tickloc : Default 'right'. Any of ['right','left','top','bottom'].
    • vertical : Boolean, default is Fasle.
    • fontsize : Default 8. Adjustable according to plot space.
  • Returns

    • cax : Matplotlib axes for colorbar, you can customize further.
  • Note: Use 'RGB_f' to map colors (after) plotted in splot_rgb_lines and use 'RGB_m' to plot DOS in same colors.

{% endraw %} {% raw %}
{% endraw %} {% raw %}
import pivotpy.s_plots as sp
import matplotlib.pyplot as plt 
plt.style.use('default')
ax = sp.get_axes(ncols=2,figsize=(4,2))
add_colorbar(ax[0],cmap_or_clist='RGB',vertical=False,N=3)
add_colorbar(ax=ax[1],cmap_or_clist=['r','g','b',4],ticklabels=['AAAA','B',"C"],N=3,tickloc='right')
plt.tight_layout()
Invalid RGBA argument: 4 
Falling back to default color map!
2022-04-24T13:54:55.694634 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/
{% endraw %} {% raw %}

color_wheel[source]

color_wheel(ax=None, xy=(1, 1), scale=0.12, rlim=(0.2, 1), N=256, colormap=None, ticks=[0.16666666666666666, 0.5, 0.8333333333333334], labels=['s', 'p', 'd'], showlegend=True)

  • Returns cax i.e. color wheel axes.
  • Parameters
    • ax : Axes on which color wheel will be drawn. Auto created if not given.
    • xy : (x,y) of center of wheel.
    • scale : Scale of the cax internally generated by color wheel.
    • rlim : Values in [0,1] interval, to make donut like shape.
    • N : Number of segments in color wheel.
    • colormap : Matplotlib's color map name. Auto picks RGB_f and if fails, fallbacks to viridis.
    • ticks : Ticks in fractions in interval [0,1].
    • labels : Ticks labels.
    • showlegend: True or False.
{% endraw %} {% raw %}
{% endraw %} {% raw %}
color_wheel(xy=(0.5,0.5),scale=0.5,colormap='hsv',ticks=[0,1/3,2/3],labels=['Red','Green','Blue'])
<matplotlib.projections.polar.PolarAxes at 0x1d0eb16b4c8>
2022-04-24T13:54:56.132125 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/
{% endraw %}

Including Atomic and Orbital Projections

{% raw %}
{% endraw %}
  • We can use _plot_collection together with arguments of _get_pros_data,_make_line_collection, see below.
{% raw %}
import time
start=time.time()
import numpy as np 
import pivotpy as pp
vr = pp.Vasprun('E:/Research/graphene_example/ISPIN_2/bands/vasprun.xml',elim=[-10,10])
k=vr.data.kpath
ef=vr.data.tdos.E_Fermi
en=vr.data.bands.evals.SpinUp-ef
pros=vr.data.pro_bands.pros.SpinUp
gpd_args = dict(kpath=k,evals_set=en,pros_set=pros,scale_data=True)
mlc_args = dict(max_width = 2.5,colors_list = None,rgb = False,uni_width = False, scale_color = False)
{% endraw %} {% raw %}
import pivotpy.s_plots as sp 
import matplotlib.pyplot as plt 
plt.style.use('seaborn')
axs = sp.get_axes(ncols=3,figsize=(8,2.6),sharey=True)
axc = axs[0].get_figure().add_axes([0.5,0.9,0.3,0.04])

gpd_args.update(elements=[[0,1],[0,1],[0,1]],orbs=[[0],[2],[1,3]])
mlc_args['colors_list'] = [(1,0,0,1),(0,1,0,1),(0,0,1,0.4)]
_plot_collection(gpd_args,mlc_args,axes=axs[0])
sp.add_legend(ax=axs[0],labels=['C-s','C-pz','C-px+py'],widths=2.5,colors=mlc_args['colors_list'])

gpd_args['orbs'] = [[0],[1,2,3],[4,5,6,7,8]]
_plot_collection(gpd_args,mlc_args,axes=axs[1])

mlc_args['uni_width'] = True
_plot_collection(gpd_args,mlc_args,axes=axs[2])

_ = [sp.modify_axes(ax=ax) for ax in axs]
add_colorbar(ax=axs[1],cax=axc,cmap_or_clist = mlc_args['colors_list'],vertical=False,ticklabels=['C-s','C-p','C-d'],ticks=[0,0.5,1])
plt.subplots_adjust(wspace=0.05)
txts=['Default/s,pz,px+py','uni_width=False/s,p,d','uni_width=True/s,p,d']
_ = [sp.add_text(ax=ax,txts=txt,xs=0.5) for ax,txt in zip(axs,txts)]
print('Executed in {} seconds.'.format(time.time()-start))
Executed in 0.29709362983703613 seconds.
2022-04-24T13:54:57.382427 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/
{% endraw %}
  • Based on _get_pros_data,_make_line_collection and _plot_collection, below are two functions splot_rgb_lines and splot_color_lines,which can be used without any hassel of changing and passing dictionary of arguments from one function to other. The difference between two is that splot_rgb_lines works with three elemenents only and generates a single variable color and variable thickness line, while splot_color_lines plots single colored as many lines as len(elements) with variable thickness.
{% raw %}
{% endraw %} {% raw %}

splot_rgb_lines[source]

splot_rgb_lines(path_evr=None, elements=[[], [], []], orbs=[[], [], []], labels=['', '', ''], ax=None, skipk=None, elim=[], max_width=None, ktick_inds=[0, -1], ktick_vals=['$\\Gamma$', 'M'], kseg_inds=[], E_Fermi=None, txt=None, xytxt=[0.2, 0.9], ctxt='black', uni_width=False, spin='both', interp_nk={}, scale_color=True, scale_data=True, colorbar=True, color_matrix=None, query_data={})

  • Returns axes object and plot on which all matplotlib allowed actions could be performed. In this function,orbs,labels,elements all have list of length 3. Inside list, sublists or strings could be any length but should be there even if empty.
  • Parameters
    • path_evr : path/to/vasprun.xml or output of export_vasprun. Auto picks in CWD.
    • elements : List [[],[],[]] by default and plots s,p,d orbital of system..
    • orbs : List [[r],[g],[b]] of indices of orbitals, could be empty, but shape should be same.
    • labels : List [str,str,str] of projection labels. empty string should exist to maintain shape. Auto adds , for ISPIN=2. If a label is empty i.e. '', it will not show up in colorbar ticks or legend.
    • ax : Matplotlib axes object, if not given, one is created.
    • skipk : Number of kpoints to skip, default will be from IBZKPT.
    • kseg_inds : Points where kpath is broken.
    • elim : [min,max] of energy range.
    • E_Fermi : If not given, automatically picked from export_vasprun.
    • ktick_inds : High symmetry kpoints indices.abs
    • ktick_vals : High Symmetry kpoints labels.
    • max_width : Width to scale whole projections. if uni_width=True, width=max_width/2. Default is None and linewidth at any point = 2.5*sum(ions+orbitals projection of all three input at that point). Linewidth is scaled to max_width if an int or float is given.
    • txt : Text on figure, if None, SYSTEM's name is printed.
    • xytxt : [x_coord,y_coord] of text relative to axes.
    • ctxt : color of text.
    • uni_width : If True, width of bands kept uniform.
    • spin : Plot spin-polarized for spin {'up','down','both'}. Default is both.
    • interp_nk : Dictionary with keys 'n' and 'k' for interpolation.
    • scale_color: Boolean. Default True, colors are scaled to 1 at each point. If False, clips colors in range [0,1] but does not effect linewidth.
    • scale_data : Default is True and normalizes projection data to 1. Has no visual effect if scale_color = True too.
    • colorbar : Default is True. Displays a vertical RGB colorbar.
    • color_matrix: Only works if scale_color==True. 3x3 or 3x4 numpy array or list to transform from RGB to another space,provided that sum(color_matrix[i,:3]) <= 1.
                4th column, if given can be used to control the saturation,contrast and brightness as s,c,b = color_matrix[:,3]
                For simply changing the color intensity use np.diag([r,g,b]) with r,g,b interval in [0,1].
                Try `pivotpy.color_matrix` as suggested color matrix and modify, which at s=0 returns gray scale.!
    • query_data : Dictionary with keys as label and values as list of length 2. Should be <= 3 for RGB plots. If given, used in place of elements, orbs and labels arguments.
                Example: {'s':([0,1],[0]),'p':([0,1],[1,2,3]),'d':([0,1],[4,5,6,7,8])} will pick up s,p,d orbitals of first two ions of system.
  • Returns
    • ax : matplotlib axes object with plotted projected bands.
    • Registers as colormap RGB_m to use in DOS to plot in same colors and RGB_f to display bands colorbar on another axes.

      Note: Two figures made by this function could be comapred quantitatively only if scale_data=False, max_width=None, scale_color=False as these parameters act internally on data.

{% endraw %} {% raw %}
{% endraw %}
  • splot_rgb_lines() is waraper around _make_line_collection(rgb=True). You can pass lists for orbs,labels, and elements each of length 3 which will be plotted on one axes.
    • If you do not provide any arguemnts, this will create graph of s orbital of first ion.
    • elements argument is special, you can pass index of element which will pick all ions of that type, or list(length=3) of indices of ions, e.g in elements=[0,[0,1],2] of system Ga32As31Bi1, 0 and 2 pick all ions of Ga and Bi respectively, while [0,1] will pick first two ions of Ga.
    • If scale_color=True, ecah point on plot is scaled to maximum color, if False, whole data is normalized if scale_data=True.
    • color_matrix is to convert between color spaces and play around as you can. Sum of each row up yo 3 columns should be less than or equal to 1. 4th column of color_matrix is for saturation, contrast and brightness from top to bottom in order. Only works if scale_color=True. {% include tip.html content='pivotpy.color_matrix and pivotpy.gray_matrix are 3x4 quick matrices.' %}{% include tip.html content='Use RGB_m for DOS and RGB_f for bands plotting in same color. RGB_f is auto-picked by add_colorbar.' %}
{% raw %}
import os
import numpy as np
import pivotpy as pp
import matplotlib.pyplot as plt
with pp.set_dir('E:/Research/graphene_example/ISPIN_2/bands'):
    vr = pp.Vasprun()
#plt.style.use('ggplot')

args_dict = dict(path_evr=vr.data,labels=['s','p$_z$','p$_x$+p$_y$'],xytxt=(0.3,0.9))

axs=get_axes(nrows=2,ncols=3,figsize=(9,5),sharex=True,sharey=True);
splot_rgb_lines(ax=axs[0,0],**args_dict,spin='up',txt='scale_color=False',scale_color=False)
splot_rgb_lines(ax=axs[0,1],**args_dict,scale_data=False,scale_color=False,spin='down',txt='scale_[color,data]=False')
splot_rgb_lines(ax=axs[0,2],**args_dict,spin='both',txt='scale_color=True')

#plt.style.use(['default','seaborn'])
_ = splot_rgb_lines(ax=axs[1,0],**args_dict,spin='up',txt='color_matrix',color_matrix=pp.color_matrix)
_ = splot_rgb_lines(ax=axs[1,1],**args_dict,spin='down',txt='color_matrix.T',color_matrix=pp.color_matrix.T)
_ = splot_rgb_lines(ax=axs[1,2],**args_dict,spin='both',txt='gray_matrix',color_matrix=pp.gray_matrix)
2022-04-24T13:54:59.601638 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/
{% endraw %} {% raw %}

splot_color_lines[source]

splot_color_lines(path_evr=None, elements=[[0]], orbs=[[0]], labels=['s'], axes=None, skipk=None, kseg_inds=[], elim=[], colormap='gist_rainbow', scale_data=False, max_width=None, spin='both', ktick_inds=[0, -1], ktick_vals=['$\\Gamma$', 'M'], E_Fermi=None, showlegend=True, xytxt=[0.2, 0.85], ctxt='black', interp_nk={}, legend_kwargs={'ncol': 4, 'anchor': (0, 1.05), 'handletextpad': 0.5, 'handlelength': 1, 'fontsize': 'small', 'frameon': False}, query_data={}, **subplots_adjust_kwargs)

  • Returns axes object and plot on which all matplotlib allowed actions could be performed. If given, elements, orbs, and labels must have same length. If not given, zeroth ion is plotted with s-orbital.
  • Parameters
    • path_evr : Path/to/vasprun.xml or output of export_vasprun. Auto picks in CWD.
    • elements : List [[0],], by defualt and plot first ion's projections.
    • orbs : List [[0],] lists of indices of orbitals, could be empty.
    • labels : List [str,] of orbitals labels. len(labels)==len(orbs) must hold. Auto adds , for ISPIN=2. If a label is empty i.e. '', it will not show up in legend.
    • axes : Matplotlib axes object with one or many axes, if not given, auto created.
    • skipk : Number of kpoints to skip, default will be from IBZKPT.
    • kseg_inds : Points where kpath is broken.
    • elim : [min,max] of energy range.
    • E_Fermi : If not given, automatically picked from export_vasprun.
    • ktick_inds : High symmetry kpoints indices.abs
    • ktick_vals : High Symmetry kpoints labels.
    • colormap : Matplotlib's standard color maps. Default is 'gist_ranibow'.
    • showlegend : True by defualt and displays legend relative to axes[0]. If False, it writes text on individual ax.
    • scale_data : Default is False, If True, normalize projection data to 1.
    • max_width : Width to scale whole projections. Default is None and linewidth at any point on a line = 2.5*sum(ions+orbitals projection of the input for that line at that point). Linewidth is scaled to max_width if an int or float is given.
    • xytxt : [x_coord,y_coord] of labels relative to axes. Works if showlegend = False.
    • ctxt : color of text of labels
    • spin : Plot spin-polarized for spin {'up','down','both'}. Default is both.
    • interp_nk : Dictionary with keys 'n' and 'k' for interpolation.
    • legend_kwargs: Dictionary containing legend arguments.
    • query_data : Dictionary with keys as label and values as list of length 2. If given, used in place of elements, orbs and labels arguments.
                Example: {'s':([0,1],[0]),'p':([0,1],[1,2,3]),'d':([0,1],[4,5,6,7,8])} will pick up s,p,d orbitals of first two ions of system.
    • **subplots_adjust_kwargs : plt.subplots_adjust parameters.
  • Returns
    • axes : matplotlib axes object [one or list of axes] with plotted projected bands.

      Note: Two figures made by this function could be comapred quantitatively only if scale_data=False, max_width=None as these parameters act internally on data.

{% endraw %} {% raw %}
{% endraw %}
  • splot_color_lines() is waraper around _make_line_collection(rgb=False,uni_width=False,scale_color = False). You can pass equal length lists for orbs,labels, and elements either with one axis or mutltiple axes of same length as orbs.
    • If you do not provide any arguemnts, this will plots-orbital of first ion.
    • elements argument is special, you can pass index of element which will pick all ions of that type, or list of indices of ions, e.g in elements=[0,[0,1],2] of system Ga32As31Bi1, 0 and 2 pick all ions of Ga and Bi respectively, while [0,1] will pick first two ions of Ga.
    • If your given len(axis)=1, all projections are plotted on single axis and you can tweak plot aesthetics, legend display etc. There are plenty of options.
    • If a label is empty i.e. '', it will not show up in legend.

Colors Selection

Instead of giving custom colors, you can use matplotlib's colormaps to be consistent. Use

plt.colormaps()

to see list of available color maps. To get a color array from a map, you can do the following:

from matplotlib.pyplot import cm
colors  = cm.hsv(np.linspace(0,1,3))
# This will give you three colors from 'hsv' map.

You can create your own colormap by a list of colors

import pivotpy as pp 
cm = pp.create_colormap('RB',['r','b])
cm(0.5) #will give you magenta color between red and blue

Note:A custom colormaps RGB is registered in session when you import pivotpy, which could be used when plotting DOS with bands of same color. An additional colormap RGB_m a at any moment would represent the latest splot_rgb_lines run.

{% raw %}
import os
path='E:/Research/graphene_example/ISPIN_2/bands'
os.chdir(path)
import pivotpy 
import importlib as imp
pp = imp.reload(pivotpy)
import matplotlib.pyplot as plt
axs = pp.get_axes(nrows=1,ncols=3,figsize=(7,2.5),sharey=True,sharex=True)
args_dict=dict(elements=[0,0,[0,1]],orbs=[0,1,[2]],labels=['s','$p_z$','$p_x$'],hspace=0.1,wspace=0.07,showlegend=True)
splot_color_lines(axes=axs[0],**args_dict,left=0.06,colormap='flag',spin='up');
splot_color_lines(axes=axs[1],**args_dict,left=0.06,colormap='Something',spin='down',scale_data=True);
splot_color_lines(axes=axs[2],**args_dict,left=0.06,colormap='RGB',spin='both',query_data={'p':[[0,1],[1,2,3]]})
axs[2].add_text(0.5,1,'query_data takes preference \nover elements, orbs and labels')
 elements[0] = 0 is converted to range(0, 2) which picks all ions of 'C'.To just pick one ion at this index, wrap it in brackets [].
 elements[1] = 0 is converted to range(0, 2) which picks all ions of 'C'.To just pick one ion at this index, wrap it in brackets [].
colormap = 'Something' not exists, falling back to default color map.
2022-04-24T13:55:01.774331 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/
{% endraw %}

Plotting Density of States

{% raw %}
{% endraw %} {% raw %}
{% endraw %}
  • Providing labels while using _collect_dos is important, it will automatically return spin up/down saymbols.
{% raw %}

splot_dos_lines[source]

splot_dos_lines(path_evr=None, elements=[[0]], orbs=[[0]], labels=['s'], ax=None, elim=[], include_dos='both', colormap='gist_rainbow', tdos_color=(0.8, 0.95, 0.8), linewidth=0.5, fill_area=True, vertical=False, E_Fermi=None, spin='both', interp_nk={}, showlegend=True, legend_kwargs={'ncol': 4, 'anchor': (0, 1), 'handletextpad': 0.5, 'handlelength': 1, 'fontsize': 'small', 'frameon': False}, query_data={})

  • Returns ax object (if ax!=False) and plot on which all matplotlib allowed actions could be performed, returns lists of energy,tdos and pdos and labels. If given,elements,orbs colors, and labels must have same length. If not given, zeroth ions is plotted with s-orbital.
  • Parameters)
    • path_evr : Path/to/vasprun.xml or output of export_vasprun. Auto picks in CWD.
    • elements : List [[0],], by defualt and plot first ion's projections.
    • orbs : List [[0],] lists of indices of orbitals, could be empty.
    • labels : List [str,] of orbitals labels. len(labels)==len(orbs) must hold. Auto adds , for ISPIN=2.
    • ax : Matplotlib axes object, if None, one is created. If False, data lists are returned.
    • include_dos: One of {'both','tdos','pdos'}.
    • elim : [min,max] of energy range.
    • E_Fermi : If not given, automatically picked from export_vasprun.
    • colormap : Matplotlib's standard color maps. Default is 'gist_ranibow'. Use 'RGB' if want to compare with splot_rgb_lines with 3 projection inputs (len(orbs)==3).
    • fill_area : Default is True and plots filled area for dos. If False, plots lines only.
    • vertical : False, If True, plots along y-axis.
    • showlegend : True by defualt.
    • spin : Plot spin-polarized for spin {'up','down','both'}. Default is both.
    • interp_nk : Dictionary with keys 'n' and 'k' for interpolation.
    • legend_kwargs: Dictionary to contain legend arguments to fix.
    • query_data : Dictionary with keys as label and values as list of length 2. If given, used in place of elements, orbs and labels arguments.
            Example: {'s':([0,1],[0]),'p':([0,1],[1,2,3]),'d':([0,1],[4,5,6,7,8])} will pick up s,p,d orbitals of first two ions of system.
  • Returns
    • ax : Matplotlib axes.
{% endraw %} {% raw %}
{% endraw %} {% raw %}
ax = splot_dos_lines(path_evr='E:/Research/graphene_example/ISPIN_2/dos/vasprun.xml',
                vertical=False,fill_area=True,showlegend=True,include_dos='pdos',linewidth=1,
                orbs=[[1,2,3],0,1],elements=[[0],0,[1]],labels=['p','s','Ion1-pz'],
                colormap='RGB',elim=[-5,5],spin='both')
 elements[1] = 0 is converted to range(0, 2) which picks all ions of 'C'.To just pick one ion at this index, wrap it in brackets [].
c:\users\mass_\appdata\local\programs\python\python37\lib\site-packages\ipykernel_launcher.py:19: DeprecationWarning:

elementwise comparison failed; this will raise an error in the future.

2022-04-24T13:55:03.962546 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/
{% endraw %}

High Display Image in Notebook

The function below plt2html is implemented for use in pivotpy-dash app to view and save SVG image directly from web app's interface. This also enables high display output in jupyter notebook.

{% raw %}

plt2html[source]

plt2html(plt_fig=None, transparent=True, dash_html=None)

  • Returns base64 encoded Image to display in notebook or HTML or plotly's dash_html_components.Img object.
  • Parameters
    • plt_fig : Matplotlib's figure instance, auto picks as well.
    • transparent: True of False for fig background.
    • dash_html : Default is None which results in an image display in jupyter notebook.
      • If True, returns html.Img object for plotly's dash.
      • If False, returns object to embed in HTML DOM.
{% endraw %} {% raw %}
{% endraw %} {% raw %}
import pivotpy as pp 
import matplotlib.pyplot as plt
pp.Vasprun("E:/Research/graphene_example/ISPIN_1/bands/vasprun.xml",elim=[-9,9]).splot_bands()
fig = plt2html(dash_html=None,transparent=False)
fig
Loading from PowerShell Exported Data...
2022-04-24T13:55:04.134422 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/
<Figure size 489.6x374.4 with 0 Axes>
{% endraw %}

Below code snippest could be used to inclue svg in html document from a figure.

data = plt2html(dash_html=False)
html_str= """
<!DOCTYPE html>
<head></head>
<body>
    <div>
    {}
    </div>
</body>
""".format(data)

with open('fig.html','w') as f:
    f.write(html_str)
{% raw %}

show[source]

show(transparent=False)

Displays all available figures in browser without blocking terminal

{% endraw %} {% raw %}

savefig[source]

savefig(filename, dpi=600, **kwargs)

Save matplotlib's figure while handling existing files. kwargs are passed to plt.savefig

{% endraw %} {% raw %}
{% endraw %} {% raw %}

plt2text[source]

plt2text(plt_fig=None, width=144, vscale=0.96, colorful=True, invert=False, crop=False, outfile=None)

Displays matplotlib figure in terminal as text. You should use a monospcae font like Cascadia Code PL to display image correctly. Use before plt.show().

  • Parameters
    • plt_fig: Matplotlib's figure instance. Auto picks if not given.
    • width : Character width in terminal, default is 144. Decrease font size when width increased.
    • vscale : Useful to tweek aspect ratio. Default is 0.96 and prints actual aspect in Cascadia Code PL. It is approximately 2*width/height when you select a single space in terminal.
    • colorful: Default is False, prints colored picture if terminal supports it, e.g Windows Terminal.
    • invert : Defult is False, could be useful for grayscale image.
    • crop : Default is False. Crops extra background, can change image color if top left pixel is not in background, in that case set this to False.
    • outfile: If None, prints to screen. Writes on a file.
{% endraw %} {% raw %}
{% endraw %}

LOCPOT/CHG Plot

{% raw %}

plot_potential[source]

plot_potential(basis=None, e_or_m=None, operation='mean_z', ax=None, period=None, lr_pos=(0.25, 0.75), lr_widths=[0.5, 0.5], labels=('$V(z)$', '$\\langle V \\rangle _{roll}(z)$', '$\\langle V \\rangle $'), colors=((0, 0.2, 0.7), 'b', 'r'), annotate=True)

  • Returns tuple(ax,Data) where Data contains resultatnt parameters of averaged potential of LOCPOT.
  • Parameters
    • basis : export_potential().basis.
    • e_or_m : epxort_potential().[e,m,m_x,m_y,m_z] is 3D grid data. As epxort_potential is slow, so compute it once and then plot the output data.
    • operation: Default is 'mean_z'. What to do with provided volumetric potential data. Anyone of these 'mean_x','min_x','max_x','mean_y','min_y','max_y','mean_z','min_z','max_z'.
    • ax: Matplotlib axes, if not given auto picks.
    • period: Periodicity of potential in fraction between 0 and 1. For example if a slab is made of 4 super cells in z-direction, period=0.25.
    • lr_pos: Locations around which averages are taken.Default (0.25,0.75). Provide in fraction between 0 and 1. Center of period is located at these given fractions. Work only if period is given.
    • lr_widths: Default is [0.5,0.5], you may have slabs which have different lengths on left and right side. Provide a pair proportional to widths e.g (1,1), (1,1.1) etc. and it is auto normalized to 1. Works only if period is given.
    • labels: List of three labels for legend. Use plt.legend() or pp.add_legend() for labels to appear. First entry is data plot, second is its convolution and third is complete average.
    • colors: List of three colors for lines.
    • annotate: True by default, writes difference of right and left averages on plot.
{% endraw %} {% raw %}
{% endraw %} {% raw %}

  Index 
  XmlElementTree 
  StaticPlots● 
  InteractivePlots 
  Utilities 
  StructureIO 
  Widgets 
  MainAPI 

{% endraw %}