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.

  Index 
  Example 
  StaticPlots● 
  InteractivePlots 
  SpinProjectedSurfaces 
  StructureIO 
  Widgets 
  MainAPI 

Passing Large Number of Arguments as a Dictionary

  • Let's take example of splot_bands. It requires a lot of 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 splot_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:
arg_dict=dict(
    path_evr=None,
    ax=None,
    skipk=None,
    kseg_inds=[],
    elim=[],
    ktick_inds=[],
    ktick_vals=[],
    Fermi=None
)
arg_dict
{'path_evr': None,
 'ax': None,
 'skipk': None,
 'kseg_inds': [],
 'elim': [],
 'ktick_inds': [],
 'ktick_vals': [],
 'Fermi': None}
  • 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 splot_bands(**arg_dict), it is usful if you run a function with same arguments many times.

Customize Matplotlib's Figure

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.

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.

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.

join_axes[source]

join_axes(ax1, ax2, **kwargs)

Join two axes together. Useful for adding custom colorbar on a long left axes of whole figure. Apply tight_layout() before calling this function. kwargs are passed to fig.add_axes.

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.
import pivotpy.splots as sp 
axs = sp.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-09-02T11:41:57.828810 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/
  • Here we will join two axes and regenerate new axes based on our grid choice.
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.splots as sp 
import matplotlib.pyplot as plt

axlarge = sp.join_axes(axs[0,0],axs[0,1])
axv = sp.join_axes(axs[1,1],axs[2,1])

sp.add_colorbar(ax=axv,cax=axlarge,vertical=False,cmap_or_clist='RGB')
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.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',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])
2022-09-02T11:41:58.627617 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/
  • A minial example below shows deleting an axes and then adding a 3D axes with same dimensions.
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-09-02T11:41:59.231128 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/

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.

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.
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-09-02T11:41:59.798225 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/

Simple Band Struture Plots

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.

splot_bands[source]

splot_bands(path_evr=None, ax=None, skipk=None, kseg_inds=[], elim=[], ktick_inds=[], ktick_vals=[], 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.
    • 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.

Example: Graphene

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

import matplotlib.pyplot as plt
import pivotpy.parser as vp
import pivotpy.splots as sp

vr1 = vp.export_vasprun(path = f1)
vr2 = vp.export_vasprun(path = f2)

ax0, ax1, ax2 = sp.get_axes(ncols=3,figsize=(8,2.6),sharey=True, sharex=True)

splot_bands(vr1, ax = ax0,color='k',color_='c',lw_ = 0.7,ls_='dashed',elim=[-20,18])
# elim above sets grid automatically, for others, we set later.

splot_bands(vr2,ax=ax1,color='y', ktick_inds=[0,30,60,-1], ktick_vals='ΓMKΓ') #,ktick_vals=['Γ','M','K','Γ'])

splot_bands(vr1, ax=ax2,color='y',label='Unpolarized',lw=3)
splot_bands(vr2, ax=ax2,color='b',color_ = 'w',lw_ = 0.5, ls_ = 'dashed',label=r'$S_\uparrow$',label_ = r'$S_\downarrow$')
ax1.set_ylabel('')
ax2.set_ylabel('')
ax1.grid(axis='x')
ax2.grid(axis='x',ls='dashed')

plt.subplots_adjust(hspace=0.01,wspace=0.05)
2022-09-02T11:42:01.238062 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/
import pivotpy.splots 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-09-02T11:42:01.844367 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/

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.

add_colorbar[source]

add_colorbar(ax, cmap_or_clist=None, N=256, ticks=None, ticklabels=None, vmin=None, vmax=None, cax=None, tickloc='right', vertical=True, digits=2, 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.
    • cmap_or_clist: List/array of colors in or colormap's name. If None (default), matplotlib's default colormap is plotted.
    • N : int, number of color points Default 256.
    • ticks : List of tick values to show on colorbar. To turn off, give [].
    • ticklabels : List of labels for ticks.
    • vmin,vmax : Minimum and maximum values. Only work if ticks are given.
    • cax : Matplotlib axes for colorbar. If not given, one is created.
    • tickloc : Default 'right'. Any of ['right','left','top','bottom'].
    • digits : Number of digits to show in tick if ticklabels are not given.
    • vertical : Boolean, default is Fasle.
    • fontsize : Default 8. Adjustable according to plot space.
  • Returns

    • cax : Matplotlib axes for colorbar, you can customize further.
import pivotpy.splots 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=15,tickloc='right')
plt.tight_layout()
Invalid RGBA argument: 4 
Falling back to default color map!
2022-09-02T11:42:02.297463 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/

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. fallbacks to hsv.
    • ticks : Ticks in fractions in interval [0,1].
    • labels : Ticks labels.
    • showlegend: True or False.
color_wheel(xy=(0.5,0.5),scale=0.5,colormap='hsv',ticks=[0,1/3,2/3],labels=['Red','Green','Blue'],showlegend=False)
<matplotlib.projections.polar.PolarAxes at 0x160b0ad7588>
2022-09-02T11:42:02.812363 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/

Including Atomic and Orbital Projections

  • Below are two functions splot_rgb_lines and splot_color_lines. The difference between the 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.

color_cube[source]

color_cube(ax, colormap='brg', loc=(1, 0.4), size=0.2, N=7, labels=['s', 'p', 'd'], color='k', fontsize=10)

Color-mapped hexagon that serves as a legend for splot_rgb_lines

ax = plt.axes()
for loc, cmap in zip([(0.6,0.1),(0.6,0.6),(0.1,0.6),(0.1,0.1)],['RGB','jet','viridis','coolwarm']):
    cax = color_cube(ax,cmap,loc=loc,size=0.3,color='red',N=4)
    cax.set_title(cmap)
2022-09-02T11:42:03.704044 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/

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=[], Fermi=None, txt=None, xytxt=[0.2, 0.9], ctxt='black', spin='both', interp_nk={}, scale_data=False, colorbar=True, colormap=None, N=9, shadow=True, 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.
    • Fermi : If not given, automatically picked from export_vasprun.
    • ktick_inds : High symmetry kpoints indices.abs
    • ktick_vals : High Symmetry kpoints labels.
    • max_width : 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.
    • spin : Plot spin-polarized for spin {'up','down','both'}. Default is both.
    • interp_nk : Dictionary with keys 'n' and 'k' for interpolation.
    • scale_data : Default is False. If True, normalizes projection data to 1.
    • colorbar : Default is True. Displays a vertical RGB colorbar. Forfine control, set it False and use plot_handle.add_colorbar and plot_handle.color_cube just afer plotting.
    • colormap : 1.2.7+, Default is None and picks suitable for each case. For all three projections given, only first, middle and last colors are used to interpolate between them.
    • N : Number of distinct colors in colormap. For given three non-zero projections, even number will be rounded up to greater odd number, so 4 and 5 are same in that case.
    • 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.

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.

  • splot_rgb_lines() requires 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, p,d orbital of the system.
    • 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.
    • Instead of elements, orbs, labels, you can use query_data = {'label: [elements list, orbs list],...}.
    • Use good colormaps that have rich variety of colors like jet, brg,....
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,xytxt=(0.3,0.9),elim=[-20,18])

axs=get_axes(nrows=2,ncols=3,figsize=(9,5),sharex=True,sharey=True)
ax = splot_rgb_lines(ax=axs[0,0],**args_dict,N =3, scale_data=False,spin='up',txt='scale_data=False',colorbar=False,colormap='RGB')
ccax = ax.color_cube(loc=(0.55,0.6),size=0.5) 
pos = ccax.get_position() # Relocate color-cube
ccax.set_position([pos.x0*1.29,pos.y0*0.9,pos.width*0.5,pos.height])

args_dict['query_data'] = {'s':[range(2),[0]],'p$_z$':[range(2),[2]],'p$_x$+p$_y$':[range(2),[1,3]]}
splot_rgb_lines(ax=axs[0,1],**args_dict,spin='up',txt='colormap = "summer"\nNot good',colormap = 'summer')

#plt.style.use(['default','seaborn'])
_ = splot_rgb_lines(ax=axs[1,0],**args_dict,spin='up',txt='colormap = "viridis"',colormap = 'viridis')
_ = splot_rgb_lines(ax=axs[1,1],**args_dict,N = 20, spin='up',txt='colormap = "jet"',colormap = 'jet')

ax_s = splot_rgb_lines(vr.data, ax=axs[0,2],spin='up',N = 3,query_data={'s':[[0],[0]]},max_width=12,txt='max_width=12',elim=[-20,18],colorbar=False)
cax = ax_s.add_colorbar(vertical=False)
cax.text(1,0.5,r' $s_ \uparrow$',ha='left',va='center',fontsize=12)
last_ax = splot_rgb_lines(vr.data, ax=axs[1,2],spin='up',query_data={'s':[[0],[0]],'p':[[0],[1,2,3]]},ktick_inds=[0,30,60,-1],ktick_vals='GMKG')
last_ax.grid(axis='x')
c:\users\mass_\appdata\local\programs\python\python37\lib\site-packages\ipykernel_launcher.py:52: DeprecationWarning:

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

2022-09-02T11:42:06.389731 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/

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', shadow=True, scale_data=False, max_width=None, spin='both', ktick_inds=[0, -1], ktick_vals=['$\\Gamma$', 'M'], 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.
    • 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.

  • splot_color_lines() requires 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.
    • Instead of elements, orbs, labels, you can use query_data = {'label: [elements list, orbs list],...}.
    • 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.

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=2,ncols=3,figsize=(7,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,elim=[-20,18],
               ktick_inds=[0,30,60,-1], ktick_vals=['$\Gamma$','M','K','$\Gamma$'],)

splot_color_lines(axes=axs[0,0],**args_dict,left=0.06,colormap='flag',spin='up');
splot_color_lines(axes=axs[0,1],**args_dict,left=0.06,colormap='Something',spin='down',scale_data=True);
splot_color_lines(axes=axs[0,2],**args_dict,left=0.06,colormap='RGB',spin='both',query_data={'p':[[0,1],[1,2,3]]})

args_dict['showlegend'] = False
splot_color_lines(axes=axs[1,:],**args_dict,left=0.06,colormap='flag',spin='up',xytxt=(0.1,0.9));
axs[0,2].add_text(0.5,1,'query_data takes preference \nover elements, orbs and labels')
 Given 0 at position 1 of sequence => 'C': range(0, 2). To just pick one ion, write it as [0].
 Given 0 at position 2 of sequence => 'C': range(0, 2). To just pick one ion, write it as [0].
colormap = 'Something' not exists, falling back to default color map.
2022-09-02T11:42:12.818507 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/

Plotting Density of States

  • Providing labels while using _collect_dos is important, it will automatically return spin up/down saymbols.

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, 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.
    • Fermi : If not given, automatically picked from export_vasprun.
    • colormap : Matplotlib's standard color maps. Default is 'gist_ranibow'.
    • 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.
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')
 Given 0 at position 2 of sequence => 'C': range(0, 2). To just pick one ion, write it as [0].
c:\users\mass_\appdata\local\programs\python\python37\lib\site-packages\ipykernel_launcher.py:20: DeprecationWarning:

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

2022-09-02T11:42:19.509794 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/

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.

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.
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
2022-09-02T11:42:20.144157 image/svg+xml Matplotlib v3.3.3, https://matplotlib.org/
<Figure size 489.6x374.4 with 0 Axes>

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)

show[source]

show(transparent=False)

Displays all available figures in browser without blocking terminal

savefig[source]

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

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

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.

LOCPOT/CHG Plot

plot_potential[source]

plot_potential(basis=None, values=None, operation='mean_c', ax=None, period=None, period_right=None, interface=None, lr_pos=(0.25, 0.75), smoothness=2, 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
    • values : epxort_potential().values is 3D grid data. As epxort_potential is slow, so compute it once and then plot the output data.
    • operation: Default is 'mean_c'. What to do with provided volumetric potential data. Anyone of these 'mean_a','min_a','max_a','mean_b','min_b','max_b','mean_c','min_c','max_c'.
    • 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.
    • period_right: Periodicity of potential in fraction between 0 and 1 if right half of slab has different periodicity.
    • 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.
    • interface: Default is 0.5 if not given, you may have slabs which have different lengths on left and right side. Provide in fraction between 0 and 1 where slab is divided in left and right halves.
    • smoothness: Default is 3. Large value will smooth the curve of potential. Only works 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.

  Index 
  Example 
  StaticPlots● 
  InteractivePlots 
  SpinProjectedSurfaces 
  StructureIO 
  Widgets 
  MainAPI