matplotlib, Python by 바죠

트랙백한 것입니다. : MATLAB

https://www.youtube.com/watch?v=UO98lJQ3QGI

파이썬은 제법 이용해왔었는데,
Matplotlib 프로젝트, 이것 처음 들어 봅니다. 조사 해보니 상당히 유용할것 같습니다.
정보에 감사드립니다. 유저가이드는 2006년 12월 버전이군요.

Numeric Python에는 익숙한데, 이런것이 있는줄 몰랐습니다. python 2.5 이상 설치되어 있다면 최적의 상황으로 볼 수 있다.

http://incredible.egloos.com/2657517
xmgrace를 활용하여 주로 그림을 그려왔다. xfig를 이용해서 변형, 종합, 편집해서 최종 그림을 만들었다.
늘 2D countour가 문제였지만. 그 이외에는 불편함 없이 살아왔다고 볼 수 있다. 만든 프로그램들의 출력파일은 xmgrace 용으로 만들어져 있다. (# 코멘트로 사용할 수 있다. 무슨 데이터 세트인지를 표시하는데 사용할 수 있다. 반면, &는 데이터 세트 사이에 새로운 데이터 세트가 올 수 있음을 표시하는 문자이다.)

매트랩은 상당히 비싼 소프트웨어라고 하더군요. 너무 부담스럽게 비싼것 같습니다. 물론, 기능은 우수하다고 들었습니다. 그래서, 많은 분들이 octave라는 것을 사용한다고도 합니다. 유사한 것인데, 무료 소프트웨어입니다.

사실, 하나만 잘 사용해도 된다고 생각할 수 있습니다. 하지만, 상황이 조금 다를 수 있습니다. 너무 많은 소프트웨어들이 존재하다 보니, 이곳에서는 이것, 저곳에서는 저것을 사용합니다. 너무 일반적인 상황이 되어 버린감이 있습니다. 다양성이 존중되는 양식으로 발전했습니다. 경험으로 보았을 때, 소프트웨어를 쉽게 얻을 수 있는것이 상당히 중요한 항목인것 같습니다. 그러한 의미에서 파이썬(무료 객체지향 인터프리터 언어, MS windows, linux 등에서 설치가능)에서 그림을 그릴 수 있다는것은 또 하나의 혜택이 아닌가 생각합니다.
-------------
http://matplotlib.sourceforge.net/
http://www.scipy.org/Cookbook/Matplotlib
matplotlib is a python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. matplotlib can be used in python scripts, the python and ipython shell (ala matlab or mathematica), web application servers, and six graphical user interface toolkits.

TEX표현이 그림에 들어갈 수 있군요.


2D plot의 핵심 문제는 contour plot이죠. 이것을 지원하는 쪽을 찾아가기 마련입니다.


여러 가지 2D 그림들을 동시에 그리는 기술은 배우기가 어렵다. 사실, xfig에서 여러 그림들을 읽어 들이고 에디팅하면 된다. 물론, 다양하게 꾸밀수 있다. 글도 넣고, 그림들도 배치하고. 따라서, 2D 그림들을 한판에서 멋있게 그리는것은 별고 공부하고 싶지않다.

TEX으로 만든 수식도 그림으로 저장된다. 이것을 그림으로 불러들여서 사용하면 얼마나 선명할까? 안해 봐서 모르겠다. (PS. 해보았는데 굉장히 선명하다.)
http://incredible.egloos.com/3632688

http://incredible.egloos.com/2411417
--------------------------------------------------------------------------------------------------------------
matplotlib 예제들:
http://matplotlib.sourceforge.net/examples/
스크린샷츠:
http://matplotlib.sourceforge.net/screenshots.html
사용설명서:
users_guide_0.90.0.pdf
api.pdf


gallery에서 그림을 클릭하면 소스를 다운로드 받을 수 있다.
Click on any image to see full size image and source code
http://matplotlib.sourceforge.net/gallery.html
갤러리에 있는 모든 그림들에 대한 "python sorce" 코드가 공개되어 있습니다.
해당 그림을 클릭하면 바로 소스 코드를 보실 수 있습니다.   아주 다양한 예제들이 즐비하다.

참고:
http://matplotlib.sourceforge.net/
http://en.wikipedia.org/wiki/Matplotlib
--------------------------------------------------------------------------------------------------------------
cf. contour그리기 스크립트
http://incredible.egloos.com/3632688


설치 방법:
 cd matplotlib-1.0.1
python setup.py build
 python setup.py install


----------------------------------------------


#   https://matplotlib.org/gallery/lines_bars_and_markers/simple_plot.html 
  2 import matplotlib                                                          
  3 import matplotlib.pyplot as plt                                            
  4 import numpy as np                                                         
  5                                                                            
  6 # Data for plotting                                                        
  7 t = np.arange(0.0, 2.0, 0.01)                                              
  8 s = 1 + np.sin(2 * np.pi * t)                                              
  9                                                                            
 10 # Note that using plt.subplots below is equivalent to using                
 11 # fig = plt.figure() and then ax = fig.add_subplot(111)                    
 12 fig, ax = plt.subplots()                                                   
 13 ax.plot(t, s)                                                              
 14                                                                            
 15 ax.set(xlabel='time (s)', ylabel='voltage (mV)',                           
 16     â  title='About as simple as it gets, folks')                         
 17 ax.grid()                                                                  
 18                                                                            
 19 fig.savefig("test.png")                                                    
 20 plt.show()                      



#  https://matplotlib.org/gallery/subplots_axes_and_figures/subplot.py                               
  2                                                                                                      
  3 import numpy as np                                                                                   
  4 import matplotlib.pyplot as plt                                                                      
  5                                                                                                      
  6                                                                                                      
  7 x1 = np.linspace(0.0, 5.0)                                                                           
  8 x2 = np.linspace(0.0, 2.0)                                                                           
  9                                                                                                      
 10 y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)                                                            
 11 y2 = np.cos(2 * np.pi * x2)                                                                          
 12                                                                                                      
 13 plt.subplot(2, 1, 1)                                                                                 
 14 plt.plot(x1, y1, 'o-')                                                                               
 15 plt.title('A tale of 2 subplots')                                                                    
 16 plt.ylabel('Damped oscillation')                                                                     
 17                                                                                                      
 18 plt.subplot(2, 1, 2)                                                                                 
 19 plt.plot(x2, y2, '.-')                                                                               
 20 plt.xlabel('time (s)')                                                                               
 21 plt.ylabel('Undamped')                                                                               
 22                                                                                                      
 23 plt.show()                          



 #  https://matplotlib.org/gallery/mplot3d/surface3d.html                                             
  2                                                                                                      
  3 from mpl_toolkits.mplot3d import Axes3D                                                              
  4 import matplotlib.pyplot as plt                                                                      
  5 from matplotlib import cm                                                                            
  6 from matplotlib.ticker import LinearLocator, FormatStrFormatter                                      
  7 import numpy as np                                                                                   
  8                                                                                                      
  9                                                                                                      
 10 fig = plt.figure()                                                                                   
 11 ax = fig.gca(projection='3d')                                                                        
 12                                                                                                      
 13 # Make data.                                                                                         
 14 X = np.arange(-5, 5, 0.25)                                                                           
 15 Y = np.arange(-5, 5, 0.25)                                                                           
 16 X, Y = np.meshgrid(X, Y)                                                                             
 17 R = np.sqrt(X**2 + Y**2)                                                                             
 18 Z = np.sin(R)                                                                                        
 19                                                                                                      
 20 # Plot the surface.                                                                                  
 21 surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,                                                    
 22     â   â   â   â   â  linewidth=0, antialiased=False)                                          
 23                                                                                                      
 24 # Customize the z axis.                                                                              
 25 ax.set_zlim(-1.01, 1.01)                       
 26 ax.zaxis.set_major_locator(LinearLocator(10))                                                        
 27 ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))                                            
 28                                                                                                      
 29 # Add a color bar which maps values to colors.                                                       
 30 fig.colorbar(surf, shrink=0.5, aspect=5)                                                             
 31                                                                                                      
 32 plt.show()              



#  https://matplotlib.org/2.0.2/examples/mplot3d/lorenz_attractor.html                               
  2                                                                                                      
  3 import numpy as np                                                                                   
  4 import matplotlib.pyplot as plt                                                                      
  5 from mpl_toolkits.mplot3d import Axes3D                                                              
  6                                                                                                      
  7                                                                                                      
  8 def lorenz(x, y, z, s=10, r=28, b=2.667):                                                            
  9     x_dot = s*(y - x)                                                                                
 10     y_dot = r*x - y - x*z                                                                            
 11     z_dot = x*y - b*z                                                                                
 12     return x_dot, y_dot, z_dot                                                                       
 13                                                                                                      
 14                                                                                                      
 15 dt = 0.01                                                                                            
 16 stepCnt = 10000                                                                                      
 17                                                                                                      
 18 # Need one more for the initial values                                                               
 19 xs = np.empty((stepCnt + 1,))                                                                        
 20 ys = np.empty((stepCnt + 1,))                                                                        
 21 zs = np.empty((stepCnt + 1,))                                                                        
 22                                                                                                      
 23 # Setting initial values                                                                             
 24 xs[0], ys[0], zs[0] = (0., 1., 1.05)            
 25                                                                                                      
 26 # Stepping through "time".                                                                           
 27 for i in range(stepCnt):                                                                             
 28     # Derivatives of the X, Y, Z state                                                               
 29     x_dot, y_dot, z_dot = lorenz(xs[i], ys[i], zs[i])                                                
 30     xs[i + 1] = xs[i] + (x_dot * dt)                                                                 
 31     ys[i + 1] = ys[i] + (y_dot * dt)                                                                 
 32     zs[i + 1] = zs[i] + (z_dot * dt)                                                                 
 33                                                                                                      
 34 fig = plt.figure()                                                                                   
 35 ax = fig.gca(projection='3d')                                                                        
 36                                                                                                      
 37 ax.plot(xs, ys, zs, lw=0.5)                                                                          
 38 ax.set_xlabel("X Axis")                                                                              
 39 ax.set_ylabel("Y Axis")                                                                              
 40 ax.set_zlabel("Z Axis")                                                                              
 41 ax.set_title("Lorenz Attractor")                                                                     
 42                                                                                                      
 43 plt.show()                         



 1 #   https://matplotlib.org/2.0.2/examples/showcase/mandelbrot.html                                   
  2                                                                                                      
  3 import numpy as np                                                                                   
  4                                                                                                      
  5 def mandelbrot_set(xmin, xmax, ymin, ymax, xn, yn, maxiter, horizon=2.0):                            
  6     X = np.linspace(xmin, xmax, xn, dtype=np.float32)                                                
  7     Y = np.linspace(ymin, ymax, yn, dtype=np.float32)                                                
  8     C = X + Y[:, None]*1j                                                                            
  9     N = np.zeros(C.shape, dtype=int)                                                                 
 10     Z = np.zeros(C.shape, np.complex64)                                                              
 11     for n in range(maxiter):                                                                         
 12     â   I = np.less(abs(Z), horizon)                                                                
 13     â   N[I] = n                                                                                    
 14     â   Z[I] = Z[I]**2 + C[I]                                                                       
 15     N[N == maxiter-1] = 0                                                                            
 16     return Z, N                                                                                      
 17                                                                                                      
 18                                                                                                      
 19 if __name__ == '__main__':                                                                           
 20     import time                                                                                      
 21     import matplotlib                                                                                
 22     from matplotlib import colors                                                                    
 23     import matplotlib.pyplot as plt                                                                  
 24                                                                                                      
 25     xmin, xmax, xn = -2.25, +0.75, 3000/2                                              
 26     ymin, ymax, yn = -1.25, +1.25, 2500/2                                                            
 27     maxiter = 200                                                                                    
 28     horizon = 2.0 ** 40                                                                              
 29     log_horizon = np.log(np.log(horizon))/np.log(2)                                                  
 30     Z, N = mandelbrot_set(xmin, xmax, ymin, ymax, xn, yn, maxiter, horizon)                          
 31                                                                                                      
 32     # Normalized recount as explained in:                                                            
 33     # https://linas.org/art-gallery/escape/smooth.html                                               
 34     # https://www.ibm.com/developerworks/community/blogs/jfp/entry/My_Christmas_Gift                 
 35                                                                                                      
 36     # This line will generate warnings for null values but it is faster to                           
 37     # process them afterwards using the nan_to_num                                                   
 38     with np.errstate(invalid='ignore'):                                                              
 39     â   M = np.nan_to_num(N + 1 -                                                                   
 40     â   â   â   â   â   â np.log(np.log(abs(Z)))/np.log(2) +                                   
 41     â   â   â   â   â   â log_horizon)                                                         
 42                                                                                                      
 43     dpi = 72                                                                                         
 44     width = 10                                                                                       
 45     height = 10*yn/xn                                             
 46     fig = plt.figure(figsize=(width, height), dpi=dpi)                                               
 47     ax = fig.add_axes([0.0, 0.0, 1.0, 1.0], frameon=False, aspect=1)                                 
 48                                                                                                      
 49     # Shaded rendering                                                                               
 50     light = colors.LightSource(azdeg=315, altdeg=10)                                                 
 51     M = light.shade(M, cmap=plt.cm.hot, vert_exag=1.5,                                               
 52     â   â   â   â   norm=colors.PowerNorm(0.3), blend_mode='hsv')                                
 53     plt.imshow(M, extent=[xmin, xmax, ymin, ymax], interpolation="bicubic")                          
 54     ax.set_xticks([])                                                                                
 55     ax.set_yticks([])                                                                                
 56                                                                                                      
 57     # Some advertisement for matplotlib                                                              
 58     year = time.strftime("%Y")                                                                       
 59     major, minor, micro = matplotlib.__version__.split('.', 2)                                       
 60     text = ("The Mandelbrot fractal set\n"                                                           
 61     â   â   "Rendered with matplotlib %s.%s, %s - http://matplotlib.org"                           
 62     â   â   % (major, minor, year))                                                                
 63     ax.text(xmin+.025, ymin+.025, text, color="white", fontsize=12, alpha=0.5)                       
 64                                                                                                      
 65     plt.show()                                                                


1 #    https://matplotlib.org/2.0.2/mpl_examples/pylab_examples/contour_demo.py                        
  2 import matplotlib                                                                                    
  3 import numpy as np                                                                                   
  4 import matplotlib.cm as cm                                                                           
  5 import matplotlib.mlab as mlab                                                                       
  6 import matplotlib.pyplot as plt                                                                      
  7                                                                                                      
  8 matplotlib.rcParams['xtick.direction'] = 'out'                                                       
  9 matplotlib.rcParams['ytick.direction'] = 'out'                                                       
 10                                                                                                      
 11 delta = 0.025                                                                                        
 12 x = np.arange(-3.0, 3.0, delta)                                                                      
 13 y = np.arange(-2.0, 2.0, delta)                                                                      
 14 X, Y = np.meshgrid(x, y)                                                                             
 15 Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)                                                 
 16 Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)                                                     
 17 # difference of Gaussians                                                                            
 18 Z = 10.0 * (Z2 - Z1)                                                                                 
 19                                                                                                      
 20                                                                                                      
 21 # Create a simple contour plot with labels using default colors.  The                                
 22 # inline argument to clabel will control whether the labels are draw                                 
 23 # over the line segments of the contour, removing the lines beneath                                  
 24 # the label                                                                                          
 25 plt.figure()                                                                    
 26 CS = plt.contour(X, Y, Z)                                                                            
 27 plt.clabel(CS, inline=1, fontsize=10)                                                                
 28 plt.title('Simplest default with labels')                                                            
 29                                                                                                      
 30                                                                                                      
 31 # contour labels can be placed manually by providing list of positions                               
 32 # (in data coordinate). See ginput_manual_clabel.py for interactive                                  
 33 # placement.                                                                                         
 34 plt.figure()                                                                                         
 35 CS = plt.contour(X, Y, Z)                                                                            
 36 manual_locations = [(-1, -1.4), (-0.62, -0.7), (-2, 0.5), (1.7, 1.2), (2.0, 1.4), (2.4, 1.7)]        
 37 plt.clabel(CS, inline=1, fontsize=10, manual=manual_locations)                                       
 38 plt.title('labels at selected locations')                                                            
 39                                                                                                      
 40                                                                                                      
 41 # You can force all the contours to be the same color.                                               
 42 plt.figure()         
 43 CS = plt.contour(X, Y, Z, 6,                                                                         
 44     â   â   â   âcolors='k',  # negative contours will be dashed by default                      
 45     â   â   â   â)                                                                               
 46 plt.clabel(CS, fontsize=9, inline=1)                                                                 
 47 plt.title('Single color - negative contours dashed')                                                 
 48                                                                                                      
 49 # You can set negative contours to be solid instead of dashed:                                       
 50 matplotlib.rcParams['contour.negative_linestyle'] = 'solid'                                          
 51 plt.figure()                                                                                         
 52 CS = plt.contour(X, Y, Z, 6,                                                                         
 53     â   â   â   âcolors='k',  # negative contours will be dashed by default                      
 54     â   â   â   â)                                                                               
 55 plt.clabel(CS, fontsize=9, inline=1)                                                                 
 56 plt.title('Single color - negative contours solid')                                                  
 57                                                                                                      
 58                                                                                                      
 59 # And you can manually specify the colors of the contour                                             
 60 plt.figure()                                                                                         
 61 CS = plt.contour(X, Y, Z, 6,                                                                         
 62     â   â   â   âlinewidths=np.arange(.5, 4, .5),                                                
 63     â   â   â   âcolors=('r', 'green', 'blue', (1, 1, 0), '#afeeee', '0.5')                      
 64                  )                                                                               
 65 plt.clabel(CS, fontsize=9, inline=1)                                                                 
 66 plt.title('Crazy lines')                                                              
 67                                                                                                      
 68                                                                                                      
 69 # Or you can use a colormap to specify the colors; the default                                       
 70 # colormap will be used for the contour lines                                                        
 71 plt.figure()                                                                                         
 72 im = plt.imshow(Z, interpolation='bilinear', origin='lower',                                         
 73     â   â   â   cmap=cm.gray, extent=(-3, 3, -2, 2))                                              
 74 levels = np.arange(-1.2, 1.6, 0.2)                                                                   
 75 CS = plt.contour(Z, levels,                                                                          
 76     â   â   â   âorigin='lower',                                                                 
 77     â   â   â   âlinewidths=2,                                                                   
 78     â   â   â   âextent=(-3, 3, -2, 2))                                                          
 79                                                                                                      
 80 # Thicken the zero contour.                                                                          
 81 zc = CS.collections[6]                                                                               
 82 plt.setp(zc, linewidth=4)                                                                            
 83                                                                                                      
 84 plt.clabel(CS, levels[1::2],  # label every second level                                             
 85     â   â  inline=1,                                                                               
 86     â   â  fmt='%1.1f',                                                                            
 87     â   â  fontsize=14)                                                                            
 88                                                                                                      
 89 # make a colorbar for the contour lines                                                              
 90 CB = plt.colorbar(CS, shrink=0.8, extend='both')                                                     
 91                                                                  
 92 plt.title('Lines with colorbar')                                                                     
 93 #plt.hot()  # Now change the colormap for the contour lines and colorbar                             
 94 plt.flag()                                                                                           
 95                                                                                                      
 96 # We can still add a colorbar for the image, too.                                                    
 97 CBI = plt.colorbar(im, orientation='horizontal', shrink=0.8)                                         
 98                                                                                                      
 99 # This makes the original colorbar look a bit out of place,                                          
100 # so let's improve its position.                                                                     
101                                                                                                      
102 l, b, w, h = plt.gca().get_position().bounds                                                         
103 ll, bb, ww, hh = CB.ax.get_position().bounds                                                         
104 CB.ax.set_position([ll, b + 0.1*h, ww, h*0.8])                                                       
105                                                                                                      
106                                                                                                      
107 plt.show()                                



eps 파일 편집 과정: eps --> eps

eps --> 벡터 양식중 하나인 emf 변환
ppt에서 벡터 양식인 emf 파일 불러들임. 그룹해체 후, 편집
최종본--> pdf 로 저장
--> acrobat 으로 pdf 파일 열고, 기타 옵션에서 eps로 저장

               
그림 프레임을 보다 더 두꺼운 선으로 처리하기
plt.rcParams['axes.linewidth'] = 1.4 #set the value globally
아래와 같이 중간 tick을 자동으로 넣어 줄 수 있다.
from matplotlib.ticker import AutoMinorLocator
ax.grid()
ax.xaxis.set_minor_locator(AutoMinorLocator())
ax.yaxis.set_minor_locator(AutoMinorLocator())





핑백

덧글

  • 택을이 2007/02/12 22:43 # 삭제 답글

    이제 그럼 xmgrace 안쓰고 이 프로그램 쓰시나 보네요?
  • 바죠 2007/02/13 08:58 # 답글

    택을이>> 아님니다. 이것은 아직 설치도 못했습니다. xmgrace가 얼마나 좋은데요. 아직까지는, xmgrace를 사용해야합니다. 문제는 2차원 contour 그림을 그릴 때는 대책이 없다는 말씀. xmgrace는 지원을 하지 않습니다.
    어떤것들이 있는지 정리하는 수준입니다.

  • 바죠 2011/03/29 16:35 # 답글


    전형적인 X-Y plot:
    http://forcecore.tistory.com/1200
  • 바죠 2019/10/08 17:25 # 답글

    수식을 표현할 때,
    뛰어쓰기는 , ;, quad, qquad
    와 같은 것을 사용한다.
    아래와 같다.

    roman character를 도입할 수 있다.
    아래와 같다.


    #ax.set_xlabel(r'$T , ({rm K})$', fontsize=22)
    #ax.set_ylabel(r'$rho(T) , {rm(muOmega cm)}$', fontsize=22)
    #ax.set_xlabel(r'$T quad ({rm K})$', fontsize=22)
    #ax.set_ylabel(r'$rho(T) quad {rm(muOmega cm)}$', fontsize=22)
    ax.set_xlabel(r'$T ; ({rm K})$', fontsize=22)
    ax.set_ylabel(r'$rho(T) ; {rm(muOmega cm)}$', fontsize=22)
  • 바죠 2020/01/10 08:01 # 답글

    그림 프레임을 보다 더 두꺼운 선으로 처리하기
    plt.rcParams['axes.linewidth'] = 1.4 #set the value globally
    아래와 같이 중간 tick을 자동으로 넣어 줄 수 있다.
    from matplotlib.ticker import AutoMinorLocator
    ax.grid()
    ax.xaxis.set_minor_locator(AutoMinorLocator())
    ax.yaxis.set_minor_locator(AutoMinorLocator())
  • 바죠 2020/04/16 15:31 # 답글

    def make_plot1(x,y,x1,y1):
    fig,ax=plt.subplots()
    ax=plt.axes()
    ax.set_xlabel(r"$2theta$",fontsize=18)
    ax.set_ylabel('intensity (arb. unit)',fontsize=18)
    majorLocator= MultipleLocator(20.0)
    minorLocator= AutoMinorLocator()
    majorFormatter= FormatStrFormatter('%d')
    minorFormatter= FormatStrFormatter('%d')
    ax.xaxis.set_major_locator(majorLocator)
    ax.xaxis.set_major_formatter(majorFormatter)
    ax.xaxis.set_minor_locator(minorLocator)
    majorLocator= MultipleLocator(0.2)
    minorLocator= AutoMinorLocator()
    majorFormatter= FormatStrFormatter('%4.2f')
    minorFormatter= FormatStrFormatter('%4.2f')
    ax.yaxis.set_major_locator(majorLocator)
    ax.yaxis.set_major_formatter(majorFormatter)
    ax.yaxis.set_minor_locator(minorLocator)
    ax.tick_params(which='major', length=2, color='black')
    ax.tick_params(which='minor', length=4, color='brown')
    plt.plot(x,y, 'o',markersize=4.5, alpha=0.3)
    plt.plot(x1,y1, '+', alpha=0.4)
    plt.legend(['C2/m', 'C2/m*'],fontsize=18)
    fig.tight_layout()
    # fig.savefig('cmp.eps')
    plt.show()
댓글 입력 영역

최근 포토로그



MathJax