--- 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" ---
_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._plot_bands?
and hit enter. This will give Signature and DocString.dict(what you copied)
. In a Jupyter Notebook cell, you can edit it: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
**
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._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.)get_axes
by using gridspec
. 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.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)
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])
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)])
Sometimes we need to display different ranges of data scattered far apart. Use fubction break_spines
defined below and see an example.
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)|$')
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.
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)
Below is example where you can add multiple text entries on a splot_bands
.
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)
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()
color_wheel(xy=(0.5,0.5),scale=0.5,colormap='hsv',ticks=[0,1/3,2/3],labels=['Red','Green','Blue'])
_plot_collection
together with arguments of _get_pros_data
,_make_line_collection
, see below.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)
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))
_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._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. 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 Ga32
As31
Bi1
, 0 and 2 pick all ions of Ga and Bi respectively, while [0,1] will pick first two ions of Ga.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
.' %}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)
_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
. 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 Ga32
As31
Bi1
, 0 and 2 pick all ions of Ga and Bi respectively, while [0,1] will pick first two ions of Ga.len(axis)=1
, all projections are plotted on single axis and you can tweak plot aesthetics, legend display etc. There are plenty of options.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 colormapRGB_m
a at any moment would represent the latestsplot_rgb_lines
run.
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')
_collect_dos
is important, it will automatically return spin up/down saymbols.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')
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.
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
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)