Tex in matplotlib [Python] by 바죠

Tex in matplotlib

수식을 가장 잘 표현하는 방법은 Tex을 사용하는 것이다.
계산 결과 정리 그림에서도 Tex 기반 수식을 사용할 수 있다면 금상첨화일것이다.
이것이 가능하다. Tex에 익숙한 사람들에게는 희소속이다. Tex에 익숙하지 않은 사람들은 시큰둥할 수밖에 없다.

아래의 matplotlib 예제를 보자.
그림에 Tex으로 작성된 수식이 함께 만들어진다는 사실에 주목하자.

컴퓨터 언어를 배우는 것은 다른 일반 언어를 배울 때와 비슷할 수 있다. 
문법과 실제 연습에서 일어나는 괴리들이 발견된다는 것이다.  
이렇게 사용해도 되는지, 안되는지 확신이 없을 때가 있는 것이다.
이러한 어색한 부분들을 없애는 것은 대단히 어렵다.  시간을 필요로 하기 때문에 어려운 것이다.

새로운 프로그램을 보면서 그 때 그 때 새롭게 문법을 확인할 수밖에 없다.
결국, 다른 사람들이 작성한 프로그램을 읽어야 한다.
모방할 수 있는 것들은 모방해야만 한다.
이것은 처음부터 알 수가 없는 것들이다.
이런 부분들이 있기 마련이다.

이러한 모방이 끝나면, 나중에, 응용에서 자연스럽게 익숙해진 구문들이 술술 나올 수 있다.


"""
Demo of TeX rendering.

You can use TeX to render all of your matplotlib text if the rc
parameter text.usetex is set. This works currently on the agg and ps
backends, and requires that you have tex and the other dependencies
described at http://matplotlib.org/users/usetex.html
properly installed on your system. The first time you run a script
you will see a lot of output from tex and associated tools. The next
time, the run may be silent, as a lot of the information is cached in
~/.tex.cache

"""
import numpy as np
import matplotlib.pyplot as plt


# Example data
t = np.arange(0.0, 1.0 + 0.01, 0.01)
s = np.cos(4 * np.pi * t) + 2

plt.rc('text', usetex=True)
plt.rc('font', family='serif')
plt.plot(t, s)

plt.xlabel(r'\textbf{time} (s)')
plt.ylabel(r'\textit{voltage} (mV)',fontsize=16)
plt.title(r"\TeX\ is Number "
          r"$\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!",
          fontsize=16, color='gray')
# Make room for the ridiculously large title.
plt.subplots_adjust(top=0.8)

plt.savefig('tex_demo')
plt.show()





"""
A part of AMADEUS protocol
Written by In-Ho Lee, KRISS, July 14, 2018.
$python energyhistogram.py
"""
import matplotlib.mathtext as mathtext
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path

fig, ax = plt.subplots()

iid=[]
volume=[]
energy=[]
kount=0
with open("csa.out", 'r') as afile:
     for line in afile:
         if(len(line.split()) == 11 and line.split()[3] == 'outcar'):
             iid.append(int(line.split()[0]))
             volume.append(float(line.split()[1]))
             energy.append(float(line.split()[2]))
             kount=kount+1
#print kount
plt.rc('text', usetex=True)
plt.rc('font', family='serif')

data=energy
# histogram our data with numpy

n, bins = np.histogram(data, 100)

# get the corners of the rectangles for the histogram
left = np.array(bins[:-1])
right = np.array(bins[1:])
bottom = np.zeros(len(left))
top = bottom + n

# we need a (numrects x numsides x 2) numpy array for the path helper
# function to build a compound path
XY = np.array([[left, left, right, right], [bottom, top, top, bottom]]).T

# get the Path object
barpath = path.Path.make_compound_path_from_polys(XY)

# make a patch out of it
patch = patches.PathPatch(barpath)
ax.add_patch(patch)

# update the view limits
ax.set_xlim(left[0], right[-1])
#ax.set_xlim(-175,-140)
ax.set_ylim(bottom.min(), top.max())

ax.set_xlabel('energy (eV)', fontsize=20)
plt.show()


"""
A part of AMADEUS protocol
Written by In-Ho Lee, KRISS, July 14, 2018.
$python volumehistogram.py
"""
import matplotlib.mathtext as mathtext
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path

fig, ax = plt.subplots()

iid=[]
volume=[]
energy=[]
kount=0
with open("csa.out", 'r') as afile:
     for line in afile:
         if(len(line.split()) == 11 and line.split()[3] == 'outcar'):
             iid.append(int(line.split()[0]))
             volume.append(float(line.split()[1]))
             energy.append(float(line.split()[2]))
             kount=kount+1
#print kount
plt.rc('text', usetex=True)
plt.rc('font', family='serif')

data=volume
# histogram our data with numpy

n, bins = np.histogram(data, 100)

# get the corners of the rectangles for the histogram
left = np.array(bins[:-1])
right = np.array(bins[1:])
bottom = np.zeros(len(left))
top = bottom + n

# we need a (numrects x numsides x 2) numpy array for the path helper
# function to build a compound path
XY = np.array([[left, left, right, right], [bottom, top, top, bottom]]).T

# get the Path object
barpath = path.Path.make_compound_path_from_polys(XY)

# make a patch out of it
patch = patches.PathPatch(barpath)
ax.add_patch(patch)

# update the view limits
ax.set_xlim(left[0], right[-1])
#ax.set_xlim(500,1000)
ax.set_ylim(bottom.min(), top.max())

ax.set_xlabel('volume (\AA$^3$)', fontsize=20)
plt.show()


"""
A part of AMADEUS protocol
Written by In-Ho Lee, KRISS, July 14, 2018.
$python energyvolume.py
"""
import matplotlib.pyplot as plt
import matplotlib.mathtext as mathtext

iid=[]
volume=[]
energy=[]
kount=0
with open("csa.out", 'r') as afile:
     for line in afile:
         if(len(line.split()) == 11 and line.split()[3] == 'outcar'):
             iid.append(int(line.split()[0]))
             volume.append(float(line.split()[1]))
             energy.append(float(line.split()[2]))
             kount=kount+1

#print kount
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
fig, ax = plt.subplots()
ax.plot(volume, energy, 'o', ms=5, lw=2, alpha=0.7, mfc='orange')
ax.grid()
#ax.set_xlim(500,1000)
#ax.set_ylim(-175,-150)
ax.set_xlabel('volume (\AA$^3$)', fontsize=20)
ax.set_ylabel('energy (eV)', fontsize=20)
plt.show()


"""
A part of AMADEUS protocol
Written by In-Ho Lee, KRISS, July 14, 2018.
$python energydensity.py
"""
import matplotlib.pyplot as plt
import matplotlib.mathtext as mathtext

iid=[]
energy=[]
density=[]
kount=0
with open("csa.out", 'r') as afile:
     for line in afile:
         if(len(line.split()) == 11 and line.split()[3] == 'outcar'):
             iid.append(int(line.split()[0]))
             energy.append(float(line.split()[2]))
             density.append(float(line.split()[10]))
             kount=kount+1

#print kount
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
fig, ax = plt.subplots()
ax.plot(density, energy, 'o', ms=5, lw=2, alpha=0.7, mfc='orange')
ax.grid()
#ax.set_xlim(500,1000)
#ax.set_ylim(-175,-150)
ax.set_xlabel('density (g/cm$^3$)', fontsize=20)
ax.set_ylabel('energy (eV)', fontsize=20)
plt.show()


"""
A part of AMADEUS protocol
Written by In-Ho Lee, KRISS, July 14, 2018.
$python structureupdate.py
"""
import matplotlib.pyplot as plt
import matplotlib.mathtext as mathtext

oldiid=[]
newiid=[]
oldenergy=[]
newenergy=[]
kount=0
with open("csa.out", 'r') as afile:
     for line in afile:
         if(len(line.split()) == 6 and line.split()[1] == 'type,'):
             kount=kount+1
             if(line.split()[0] == 'old'):
                   oldiid.append(kount)
                   oldenergy.append(float(line.split()[3]))
             if(line.split()[0] == 'new'):
                   newiid.append(kount)
                   newenergy.append(float(line.split()[3]))

#print kount
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
fig, ax = plt.subplots()
ax.plot(oldiid, oldenergy, 'o', ms=5, lw=2, alpha=0.7, mfc='orange')
ax.plot(newiid, newenergy, '*', ms=5, lw=2, alpha=0.7, mfc='blue')
ax.grid()
#ax.set_xlim(1,1000)
#ax.set_ylim(-175,-150)
ax.set_xlabel('structure update', fontsize=20)
ax.set_ylabel('energy (eV)', fontsize=20)
plt.show()

"""
import matplotlib.pyplot as plt
import matplotlib.mathtext as mathtext

oldiid=[]
newiid=[]
oldenergy=[]
newenergy=[]
oldenergybefore=[]
newenergybefore=[]
kount=0
with open("csa.out", 'r') as afile:
     for line in afile:
         if(len(line.split()) == 6 and line.split()[1] == 'type,'):
             kount=kount+1
             if(line.split()[0] == 'old'):
                   oldiid.append(kount)
                   oldenergy.append(float(line.split()[3]))
                   oldenergybefore.append(float(line.split()[4]))
             if(line.split()[0] == 'new'):
                   newiid.append(kount)
                   newenergy.append(float(line.split()[3]))
                   newenergybefore.append(float(line.split()[4]))
#print kount
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
fig, ax = plt.subplots()
ax.plot(oldiid, oldenergybefore, 'x')
ax.plot(oldiid, oldenergy, 'o')
ax.plot(newiid, newenergybefore, '+')
ax.plot(newiid, newenergy, '*')
ax.grid()
#ax.set_xlim(1,1000)
# modify the y axis limits shown below.
ax.set_ylim(-175,-155)
ax.set_xlabel('structure update', fontsize=20)
ax.set_ylabel('energy (eV)', fontsize=20)
plt.show()



import glob
import numpy as np
from matplotlib import pyplot as plt
import matplotlib as mpl
from matplotlib.ticker import (MultipleLocator, AutoMinorLocator)
def get_sorted_energies(apath):
    print(apath)
    bpath=apath+'/CONTCAR_*'
    files = glob.glob(bpath)
    energies=[]
    volumes=[]
    f0=[]
    for bfile in files:
        f0.append(bfile)
        afile=open(bfile,'r')
        i=0
        for line in afile:
            if i == 0:
                etot=float(line.split()[-1])
            if i == 1:
                scale=float(line.split()[0])
            if i == 2:
                zzz=np.zeros((3,3))
                zzz[0,0]=float(line.split()[0])*scale
                zzz[0,1]=float(line.split()[1])*scale
                zzz[0,2]=float(line.split()[2])*scale
            if i == 3:
                zzz[1,0]=float(line.split()[0])*scale
                zzz[1,1]=float(line.split()[1])*scale
                zzz[1,2]=float(line.split()[2])*scale
            if i == 4:
                zzz[2,0]=float(line.split()[0])*scale
                zzz[2,1]=float(line.split()[1])*scale
                zzz[2,2]=float(line.split()[2])*scale
                det = np.linalg.det(zzz)
                det = np.abs(det)
            if i == 6:
                deno=int(line.split()[0])
#               print(etot,deno)
                etot=etot/deno
#               print(etot)
                energies.append(etot)
                volumes.append(det)
            i=i+1
        afile.close()
    energies=np.array(energies)
    volumes=np.array(volumes)
    ind=np.argsort(energies)
    if False:
        for i in ind:
            print(i,energies[i])
    x=np.zeros(len(ind))
    y=np.zeros(len(ind))
    v=np.zeros(len(ind))
    f=[]
    j=0
    for i in ind:
        x[j]=j
        y[j]=energies[i]
        v[j]=volumes[i]/deno
        f.append(f0[i])
        j=j+1
    for k in range(10):
        print(x[k],y[k],deno,v[k],f[k])
    return x,y,deno,v,f

plt.rcParams['figure.figsize'] = (10,10)
plt.rcParams['figure.dpi'] = 72
plt.rcParams['lines.linewidth'] = 6
plt.rcParams['axes.grid'] = True
plt.rcParams['savefig.dpi'] = 200
plt.rcParams['savefig.transparent'] = True
#plt.rcParams['font.family'] = 'Dejavu Sans'
plt.rcParams['font.family'] = 'Times New Roman'
mpl.rcParams['text.usetex'] = True
plt.rcParams['font.size'] = 22
plt.rcParams


fig, ax = plt.subplots()

apath='/home/ihlee/rdfsearch/fingerprintdiff/si_test_tinv/work1'
x,y,deno,v,f=get_sorted_energies(apath)
ax.scatter(x,y,color='r', marker='o', s=10, alpha=0.6, label=str(deno))

apath='/home/ihlee/rdfsearch/fingerprintdiff/si_test_tinv/work2'
x,y,deno,v,f=get_sorted_energies(apath)
ax.scatter(x,y,color='g', marker='_', s=10, alpha=0.6, label=str(deno))

apath='/home/ihlee/rdfsearch/fingerprintdiff/si_test_tinv/work3'
x,y,deno,v,f=get_sorted_energies(apath)
ax.scatter(x,y,color='b', marker='.', s=10, alpha=0.6, label=str(deno))

apath='/home/ihlee/rdfsearch/fingerprintdiff/si_test_tinv/work4'
x,y,deno,v,f=get_sorted_energies(apath)
ax.scatter(x,y,color='c', marker=',', s=10, alpha=0.6, label=str(deno))

apath='/home/ihlee/rdfsearch/fingerprintdiff/si_test_tinv/work6'
x,y,deno,v,f=get_sorted_energies(apath)
ax.scatter(x,y,color='m', marker='v', s=10, alpha=0.6, label=str(deno))

apath='/home/ihlee/rdfsearch/fingerprintdiff/si_test_tinv/work7'
x,y,deno,v,f=get_sorted_energies(apath)
ax.scatter(x,y,color='y', marker='^', s=10, alpha=0.6, label=str(deno))

apath='/home/ihlee/rdfsearch/fingerprintdiff/si_test_tinv/work8'
x,y,deno,v,f=get_sorted_energies(apath)
ax.scatter(x,y,color='lime', marker='x', s=10, alpha=0.6, label=str(deno))

apath='/home/ihlee/rdfsearch/fingerprintdiff/si_test_tinv/work9'
x,y,deno,v,f=get_sorted_energies(apath)
ax.scatter(x,y,color='navy', marker='d', s=10, alpha=0.6, label=str(deno))

apath='/home/ihlee/rdfsearch/fingerprintdiff/si_test_tinv/work10'
x,y,deno,v,f=get_sorted_energies(apath)
ax.scatter(x,y,color='gold', marker='|', s=10, alpha=0.6, label=str(deno))

apath='/home/ihlee/rdfsearch/fingerprintdiff/si_test_tinv/work11'
x,y,deno,v,f=get_sorted_energies(apath)
ax.scatter(x,y,color='orange', marker='h', s=10, alpha=0.6, label=str(deno))

apath='/home/ihlee/rdfsearch/fingerprintdiff/si_test_tinv/work12'
x,y,deno,v,f=get_sorted_energies(apath)
ax.scatter(x,y,color='violet', marker='s', s=10, alpha=0.6, label=str(deno))


ax.xaxis.set_major_locator(MultipleLocator(20))
ax.xaxis.set_minor_locator(MultipleLocator(5))
ax.xaxis.set_major_formatter('{x:.0f}')
ax.yaxis.set_major_locator(MultipleLocator(0.20))
ax.yaxis.set_minor_locator(MultipleLocator(0.05))
ax.yaxis.set_major_formatter('{x:.02f}')

ax.set_facecolor('ivory')
plt.xlabel("Structure", fontsize = 26)
plt.ylabel("Energy (eV/f.u.)", fontsize = 26)
plt.legend()
plt.tight_layout()
plt.show()



핑백

덧글

댓글 입력 영역

최근 포토로그



MathJax