티스토리 뷰

beginner/파이썬 기초

Matplotlib

johh 2019. 2. 19. 13:40
2019.02.20-2

matplotlib

시각화의 중요성과 matplotlib

  • 인간은 가장 시각 능력이 뛰어난 동물 중의 하나이다.
  • 하지만 인간의 수치 계산 능력은 본능이 아니다. (언어의 발달로 인한 논리 능력의 확장임)
  • 이런 점들이 인간이 아직까지 인공지능에 비해 시각적 판단이 뛰어난 이유이다.
  • 시각 능력은 다른 말로 하면 패턴인식 능력이다. 빛의 분포로 생기는 시각 패턴을 인간은 너무나 쉽게 알아 볼 수 있다.
  • 이러한 인간의 능력을 최대한 발휘하기 위해서 숫자로 되어 있는 데이터를 시각화 하여야 한다.
  • 제공받은 데이터의 특성을 분석하기 위해서 뿐만 아니라, 결과를 설명하기 위해서 시각화는 아주 중요하다.
  • matplotlib 는 파이썬의 시각화 도구이다.
  • matplotlib 는 MATLAB 의 시각화 기능을 참고하여 만들어졌다.
  • matplotlib 는 3차원 시각화 도구를 제공하지만 평면 상에서 3차원 도표는 알아보기 쉽지 않으므로, 대부분의 시각화 기능은 2차원을 위주로 한다.
In [1]:
import numpy as np
import matplotlib.pyplot as plt
In [2]:
plt.plot([10,12,13,14])
plt.ylim(0,20)  # xlim 도 있다.
Out[2]:
(0, 20)
In [3]:
plt.show()

[주의]

  • %pylab inline 또는 %matplotlib inline 을 실행하면 ipython 과 쥬피터 노트북에서 plt.show() 를 실행하지 않아도 되고 도표가 실행창에 포함된다.
In [4]:
%pylab inline
Populating the interactive namespace from numpy and matplotlib
In [5]:
plt.plot([1,2,3,4])
Out[5]:
[<matplotlib.lines.Line2D at 0xac890a40b8>]
In [6]:
plt.plot([1,2,3,4])
plt.plot([40,30,20,10]) #직선 두개의 최대 최소값을 기준으로 범위를 잡는다.
Out[6]:
[<matplotlib.lines.Line2D at 0xac88c7ae10>]
In [7]:
plt.plot([1,2,3,4], label='up')
plt.plot([4,3,2,1], label='down')
plt.legend(loc='center right')
Out[7]:
<matplotlib.legend.Legend at 0xac891eff98>
In [8]:
plt.plot([1,2,3,4])
plt.plot([4,3,2,1])
plt.legend(['up','down'],loc='center right')
Out[8]:
<matplotlib.legend.Legend at 0xac89326e10>

help(plt.legend)

   legend()
   legend(labels)
   legend(handles, labels)
In [9]:
plt.plot([1,2,3,4], label='up')
plt.plot([4,3,2,1], label='down')
plt.legend(loc='best')
plt.axis([-1,4,0,5])
Out[9]:
[-1, 4, 0, 5]
  • 도표에 제목을 붙이자.
In [10]:
plt.plot([1,2,3,4], label='up')
plt.plot([4,3,2,1], label='down')
plt.legend(loc='best')
plt.axis([-1,4,0,5])

plt.title('UP and DOWN lines', fontsize=20)
plt.xlabel('X')
plt.ylabel('value')
Out[10]:
Text(0,0.5,'value')
  • 이미지 크기를 변경하자.
In [11]:
fig = plt.figure(figsize=[12,8]) #그림판의 크기 설정

plt.plot([1,2,3,4], label='up')
plt.plot([4,3,2,1], label='down')
plt.legend(loc='best')
plt.axis('scaled')
plt.axis([-1,4,0,5])
#plt.xlim(-1,4)
#plt.ylim(0,5)

plt.title('UP and DOWN lines', fontsize=20)
plt.xlabel('X')
plt.ylabel('value')

plt.xticks([0, 1.5, 3],['one','1 1/2', 'three'])
plt.yticks(np.arange(1,4.1,0.5))
plt.grid()  # 격자
In [12]:
a=np.random.randn(100)

plt.plot(a)
plt.plot(a.cumsum())  #cumsum은 누적합계를 의미한다. [1,2,3,...]같은 경우 [1,3,6,...]
plt.legend(['original','cumsum'])
Out[12]:
<matplotlib.legend.Legend at 0xac894bdeb8>
In [13]:
plt.plot(a, 'b:') # color='b', linestyle='--'
plt.plot(a.cumsum(), 'gD-') # color='red', marker='o', linestyle='-'
plt.legend(['original','cumsum'], loc='best')
Out[13]:
<matplotlib.legend.Legend at 0xac895d6b70>
In [14]:
plt.plot(a[:10], 'r^-', linewidth=3, markersize=10)
plt.plot(a[:10], 'g:', drawstyle='steps-post')
Out[14]:
[<matplotlib.lines.Line2D at 0xac893ae9b0>]
In [15]:
plt.plot([0,1,2,3], label='p1')
plt.plot([1,2,3,4])
plt.plot([2,3,4,5], label='p3')

plt.xticks(range(4),['Jang gil san','hong gil dong','lee soon sin'],rotation=90, ha='center')
plt.legend()
Out[15]:
<matplotlib.legend.Legend at 0xac88de8fd0>
In [16]:
plt.plot([1,3,2,4], [1,2,3,4]) # 인자를 생략하면 y값에 대해 그려진다. x는 알아서.
plt.axis([0,5,0,5])
Out[16]:
[0, 5, 0, 5]
In [17]:
a = np.array([[1,2,3],[10,11,12]])
plt.plot(a) # 열 단위로 그린다(칼럼 개수만큼 그림을 그린다.)

plt.figure() # 전체 그림을 리셋한다
plt.plot(a.T)
Out[17]:
[<matplotlib.lines.Line2D at 0xac8a68add8>,
 <matplotlib.lines.Line2D at 0xac8a68af28>]
In [18]:
a = np.array([[1,2,3],[10,11,12]])
plt.plot(a) # 열 단위로 그린다

plt.plot(a.T)
Out[18]:
[<matplotlib.lines.Line2D at 0xac8965b320>,
 <matplotlib.lines.Line2D at 0xac8965bac8>]

scatter() 함수

  • 산점도 그림을 그린다.
  • 보통 속성이 2개인 샘플들의 위치를 점으로 찍는다.
In [19]:
a = np.array([[1,1], [2,3], [3,2]])
plt.scatter(a[:,0], a[:,1]) # 각각 X축과 Y축
Out[19]:
<matplotlib.collections.PathCollection at 0xac8a72c550>
In [20]:
f = open('iris.csv')

line = f.readline()
features = line.strip().split(',')[:4]

labels = ['Iris-setosa', 'Iris-versicolor', 'Iris-virginica']

data = []
for line in f:
    l = line.strip().split(',')
    l[:4] = [float(i) for i in l[:4]]
    l[4] = labels.index(l[4])
    
    data.append(l)

f.close()

iris = np.array(data)
In [21]:
plt.figure(figsize=[10,6])
plt.scatter(iris[:,0],iris[:,3], c=iris[:,-1], s=iris[:,2]*50, alpha=0.5,
           cmap='viridis') # 색 유형을 바꾼다.
plt.axis('equal')
plt.colorbar() #색에 의해 이름이 결정되고, 원의 크기에 의해 꽃잎 길이가 결정. (sepal width제외하고 다 들어감, 4차원) 
Out[21]:
<matplotlib.colorbar.Colorbar at 0xac8a7d2908>
In [22]:
x = np.random.rand(1000)
y = np.random.rand(1000)
plt.scatter(x,y, alpha=0.2)
plt.axis('equal')
Out[22]:
(-0.05959932422426336,
 1.059045262162267,
 -0.06137933660619447,
 1.0646839860275332)
In [23]:
x = np.random.randn(1000)   # 머신러닝을 하기 위해서 샘플 데이터를 만드는 것은 정말 중요하다.
y = np.random.randn(1000)   # x,y라는 속성이 2개 있다. 샘플은 1000개.
plt.scatter(x,y, alpha=0.2)
plt.axis('equal')
Out[23]:
(-3.4086496856023283,
 3.339779727946347,
 -3.3804682812351063,
 3.9457815781962213)
In [40]:
x1 = np.random.normal(0,1,1000)   # 샘플에 대해서 x,y뿐만 아니라 타겟값까지 넣고 싶다.
y1 = np.random.normal(0,1,1000)   # 1000개의 샘플에 대해서x1,y1,타겟(red)
plt.scatter(x1,y1, color='red', alpha=0.1)

x2 = np.random.normal(5,3,1000)
y2 = np.random.normal(3,2,1000)  # 또다른 샘플 1000개에 대해서 x2,y2,타겟(blue)
plt.scatter(x2,y2, color='blue', alpha=0.1)

plt.legend(['one','two'])  

# 데이터를 만드는 방법
# d1 = np.c_[x1,y1], d2 = np.c_[x2,y2]
# d=np.r_[d1,d2], l = [0]*1000 + [1]*1000

# x1,y1에 대한 데이터와 x2,y2에 대한 데이터를 r_,c_을 이용해 연결할수도 있지만,
# 미리 데이터가 들어갈 틀을 만들어 놓고 각각을 집어넣어도 된다. ex) a[:1000,0]=x1
Out[40]:
<matplotlib.legend.Legend at 0xac8b4da5f8>
In [41]:
x = np.random.randn(1000)
y = 2*x + 1 + np.random.randn(1000) # 2x+1로부터 아래위로 조금씩의 변화를 준다.
plt.scatter(x,y,alpha=0.2)
plt.vlines([0],-10,10, linestyles=':')
plt.hlines([0],-6,6, linestyles=':')
plt.axis('equal')

# 어떤 그래프에 근사하며 점들이 중앙으로 모이느 그래프
# 점들이 균등하게 퍼져 있을수도 있고, 그래프에만 근사하게 모여있을수도 있다.
# 다음 그림은 두 변수간에 비례함을 보여준다.
Out[41]:
(-6.6, 6.6, -11.0, 11.0)
In [26]:
x = np.random.rand(1000)
y = 2*x + 1 + np.random.rand(1000) 
plt.scatter(x,y,alpha=0.2)
plt.vlines([0],0,4, linestyles=':')
plt.hlines([0],-1,2, linestyles=':')
plt.axis('equal')

#모양을 잘 생각해보자.
Out[26]:
(-1.15, 2.15, -0.2, 4.2)
In [27]:
x = np.random.rand(1000)
y = 2*x + 1 + np.random.randn(1000) 
plt.scatter(x,y,alpha=0.2)
plt.vlines([0],-3,6, linestyles=':')
plt.hlines([0],-1,2, linestyles=':')
plt.axis('equal')
Out[27]:
(-1.15, 2.15, -3.45, 6.45)
In [42]:
x = np.random.randn(1000)
y = 2*x + 1 + np.random.rand(1000) 
plt.scatter(x,y,alpha=0.2)
plt.vlines([0],-10,10, linestyles=':')
plt.hlines([0],-6,6, linestyles=':')
plt.axis('equal')
Out[42]:
(-6.6, 6.6, -11.0, 11.0)
In [29]:
x = np.random.normal(0,0.1,1000)
y = 2*x + 1 + np.random.normal(0,0.1,1000) 
plt.scatter(x,y,alpha=0.2)
plt.vlines([0],0,2, linestyles=':')
plt.hlines([0],-1,1, linestyles=':')
plt.axis('equal') 
Out[29]:
(-1.1, 1.1, -0.1, 2.1)
In [44]:
x = np.random.randn(1000)
y = x**2 + np.random.randn(1000) 
plt.scatter(x,y,alpha=0.2)
plt.vlines([0],-4,16, linestyles=':')
plt.hlines([0],-5,5, linestyles=':')
plt.axis('equal')
Out[44]:
(-5.5, 5.5, -5.0, 17.0)
In [47]:
x = np.random.normal(0,2,1000)
y = x**2 + 1 + np.random.randn(1000)
plt.scatter(x,y,alpha=0.1)
plt.axis('equal')
Out[47]:
(-6.987439558479939, 6.750612748975652, -3.568419953647558, 44.114738697465654)
In [31]:
x = np.random.randn(100)
y = np.random.randn(100)
label = np.random.randint(2, size=100)  #randint가 2이므로 2이하값인 0또는 1값이 뽑힌다. 
sz = np.random.rand(100)*100

plt.scatter(x, y, c=label, s=sz) # 컬러와 사이즈 지정
plt.colorbar()
Out[31]:
<matplotlib.colorbar.Colorbar at 0xac8b060518>

한글 출력

In [32]:
import matplotlib.font_manager as fm

prop=fm.FontProperties(fname='C:/Windows/Fonts/gulim.ttc') 
# 해당폴더에 들어가서 '굴림xx' 파일 속성을 눌러보면 'gulim'이라고 파일 이름이 나온다.


# prop=fm.FontProperties(fname='C:/Windows/Fonts/Daum_Regular.ttf')
# prop=fm.FontProperties('Daum')  << 되는게 있고 안되는게 있다.

plt.title('헬로 플롯! (Hello, plot!)', fontproperties=prop, fontsize=20)
# fontproperties 뒤에 fontsize 가 나와야 함

plt.scatter(np.random.randn(100), np.random.randn(100), c=np.random.randn(100), s=50, alpha=0.5)
plt.xlabel('안녕하세요', fontproperties=prop)
plt.legend(['하나'], prop=prop) #레전드는 prop으로 지정해야 한다. 
Out[32]:
<matplotlib.legend.Legend at 0xac8b0c6fd0>

막대 그래프

  • bar(), barh()
In [33]:
plt.bar(range(20), np.random.randint(10,size=20), color='#00ff00')
Out[33]:
<BarContainer object of 20 artists>
In [34]:
plt.barh(range(10), np.random.randint(10,size=10)) # h는 옆으로
Out[34]:
<BarContainer object of 10 artists>
In [35]:
a = np.random.randint(10,size=10)
b = np.random.randint(10,size=10)

plt.bar(range(10), a, color='blue')
plt.bar(range(10), b, bottom=a, color='pink')      # 누적막대그래프 bottom = a 파란색 위에 분홍색을 그리겠다.
plt.legend(['Man', 'Woman'])
Out[35]:
<matplotlib.legend.Legend at 0xac8b2170b8>

히스토그램

  • 값들을 구간으로 나눠서 갯수를 막대그래프로 보여준다.
In [36]:
a = np.random.randn(10000)
display(a.max(), a.min())
plt.hist(a, bins=30, range=[-3,3])  # -3에서 3까지 30개로 나눈다.
4.312811288512504
-3.750830609419838
Out[36]:
(array([ 17.,  19.,  38.,  40., 109., 118., 196., 270., 340., 429., 579.,
        641., 686., 682., 746., 785., 758., 730., 650., 490., 493., 333.,
        276., 190., 132., 104.,  60.,  34.,  21.,   8.]),
 array([-3. , -2.8, -2.6, -2.4, -2.2, -2. , -1.8, -1.6, -1.4, -1.2, -1. ,
        -0.8, -0.6, -0.4, -0.2,  0. ,  0.2,  0.4,  0.6,  0.8,  1. ,  1.2,
         1.4,  1.6,  1.8,  2. ,  2.2,  2.4,  2.6,  2.8,  3. ]),
 <a list of 30 Patch objects>)
In [37]:
a = np.random.randint(100,size=10000) 
plt.hist(a, bins=range(0,101,5))
plt.xticks(range(0,101,5), rotation=90) #눈금 지정. 0에서 100까지 5마다. 겹치지 않게 눈금 이름은 90도 돌려서.
print('')

In [49]:
a = np.random.randn(1000)
b = np.random.normal(10,5,size=1000)
_, c = np.histogram(np.r_[a,b], 50) # 두개의 샘플을 합쳐서 구간을 나눴다.

plt.hist(a, bins=c, alpha=0.3)
plt.hist(b, bins=c, alpha=0.3)
plt.legend(['zero', 'one'])

#일차원 그림이다. 산점도를 이용해서 2차원에서 비교할 수 있다.
Out[49]:
<matplotlib.legend.Legend at 0xac8c5ad320>
In [50]:
a = np.random.randn(1000)
b = np.random.normal(10,5,size=1000)
bins = np.histogram(np.r_[a,b], 50) #_.를 떼면 오류, 튜플 안에 값이 2개 있으므로

plt.hist(a, bins=bins, alpha=0.3)
plt.hist(b, bins=bins, alpha=0.3)
plt.legend(['zero', 'one'])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-50-b0e020f23fed> in <module>()
      3 bins = np.histogram(np.r_[a,b], 50) #_.를 떼면 오류, 튜플 안에 값이 2개 있으므로
      4 
----> 5 plt.hist(a, bins=bins, alpha=0.3)
      6 plt.hist(b, bins=bins, alpha=0.3)
      7 plt.legend(['zero', 'one'])

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\pyplot.py in hist(x, bins, range, density, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, normed, hold, data, **kwargs)
   3130                       histtype=histtype, align=align, orientation=orientation,
   3131                       rwidth=rwidth, log=log, color=color, label=label,
-> 3132                       stacked=stacked, normed=normed, data=data, **kwargs)
   3133     finally:
   3134         ax._hold = washold

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs)
   1853                         "the Matplotlib list!)" % (label_namer, func.__name__),
   1854                         RuntimeWarning, stacklevel=2)
-> 1855             return func(ax, *args, **kwargs)
   1856 
   1857         inner.__doc__ = _add_data_doc(inner.__doc__,

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in hist(***failed resolving arguments***)
   6528             # this will automatically overwrite bins,
   6529             # so that each histogram uses the same bins
-> 6530             m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs)
   6531             m = m.astype(float)  # causes problems later if it's an int
   6532             if mlast is None:

C:\ProgramData\Anaconda3\lib\site-packages\numpy\lib\function_base.py in histogram(a, bins, range, normed, weights, density)
    723     elif np.ndim(bins) == 1:
    724         bin_edges = np.asarray(bins)
--> 725         if np.any(bin_edges[:-1] > bin_edges[1:]):
    726             raise ValueError(
    727                 '`bins` must increase monotonically, when an array')

ValueError: operands could not be broadcast together with shapes (50,) (51,) 
In [51]:
a = np.random.randn(1000)
b = np.random.normal(10,5,size=1000)
_, bins = np.histogram(np.r_[a,b], 50)

plt.hist(a, alpha=0.3)
plt.hist(b, alpha=0.3)
plt.legend(['zero', 'one'])

#일차원 그림이다. 산점도를 이용해서 2차원에서 비교할 수 있다.
Out[51]:
<matplotlib.legend.Legend at 0xac8c60c668>
In [52]:
result = np.histogram(np.r_[a,b], 50)
type(result), len(result)
Out[52]:
(tuple, 2)
In [53]:
_, bins
Out[53]:
(array([  1,   0,   1,   0,   0,   1,   0,   4,  17,  53, 131, 192, 257,
        228, 110,  62,  24,  17,  28,  30,  25,  25,  28,  44,  56,  45,
         49,  51,  49,  51,  44,  40,  61,  40,  39,  34,  30,  25,  29,
         16,  15,  13,  10,   8,   5,   3,   4,   3,   0,   2], dtype=int64),
 array([-7.7708751 , -7.14675601, -6.52263691, -5.89851782, -5.27439872,
        -4.65027963, -4.02616053, -3.40204144, -2.77792234, -2.15380325,
        -1.52968415, -0.90556506, -0.28144596,  0.34267313,  0.96679223,
         1.59091132,  2.21503042,  2.83914951,  3.46326861,  4.0873877 ,
         4.7115068 ,  5.33562589,  5.95974499,  6.58386408,  7.20798318,
         7.83210227,  8.45622137,  9.08034046,  9.70445956, 10.32857866,
        10.95269775, 11.57681685, 12.20093594, 12.82505504, 13.44917413,
        14.07329323, 14.69741232, 15.32153142, 15.94565051, 16.56976961,
        17.1938887 , 17.8180078 , 18.44212689, 19.06624599, 19.69036508,
        20.31448418, 20.93860327, 21.56272237, 22.18684146, 22.81096056,
        23.43507965]))
In [54]:
bins
Out[54]:
array([-7.7708751 , -7.14675601, -6.52263691, -5.89851782, -5.27439872,
       -4.65027963, -4.02616053, -3.40204144, -2.77792234, -2.15380325,
       -1.52968415, -0.90556506, -0.28144596,  0.34267313,  0.96679223,
        1.59091132,  2.21503042,  2.83914951,  3.46326861,  4.0873877 ,
        4.7115068 ,  5.33562589,  5.95974499,  6.58386408,  7.20798318,
        7.83210227,  8.45622137,  9.08034046,  9.70445956, 10.32857866,
       10.95269775, 11.57681685, 12.20093594, 12.82505504, 13.44917413,
       14.07329323, 14.69741232, 15.32153142, 15.94565051, 16.56976961,
       17.1938887 , 17.8180078 , 18.44212689, 19.06624599, 19.69036508,
       20.31448418, 20.93860327, 21.56272237, 22.18684146, 22.81096056,
       23.43507965])
In [55]:
sum([  1,   0,   1,   1,   0,   2,   2,  11,  37, 115, 239, 253, 224,
        119,  59,  25,  20,  20,  30,  32,  44,  43,  42,  50,  52,  47,
         58,  46,  58,  48,  41,  34,  43,  37,  34,  27,  24,  11,  24,
         11,   6,   7,   8,   5,   3,   1,   1,   1,   2,   1])
Out[55]:
2000
In [56]:
e,f = 1,2 # (e,f)=(1,2)
e, f
Out[56]:
(1, 2)

박스 플롯

In [57]:
a = np.zeros([100,3])
a[:,0] = np.random.randn(100)
a[:,1] = np.random.normal(5,2,size=100)
a[:,2] = np.random.normal(10,5,size=100)

plt.boxplot(a)   # 2차원 데이터를 그냥 집어넣으면 된다.
print('')

In [58]:
plt.boxplot(iris)
print('') # 글씨 삭제. 그림은 무조건 나와. pass도 가능(아무것도 하지마라)
# 속성이 아주 많을때 사용하기에 좋음

In [59]:
n=1
if n==0:
    pass
else:
    print(f)
2

imshow()

  • 2차원 형태의 데이터가 있을 때, 2차원 좌표상에서 그림을 그린다.
  • 이미지 출력에도 사용된다.
In [60]:
a = np.random.randn(64,64)
plt.imshow(a)
plt.colorbar(shrink=0.7) # colorbar의 길이를 조정
Out[60]:
<matplotlib.colorbar.Colorbar at 0xac8c7f75c0>
In [61]:
a = np.random.randn(64,64)
plt.imshow(a, interpolation='none', vmin=-1, vmax=1, cmap='gray') # interpolation 번짐효과 none을 하면 번짐효과가 없다.
# vmin vmax colorbar의 최소값과 최대값을 조정. 1보다 큰값은 1의, -1보다 작은값은 -1의 색을 따른다.
plt.colorbar(shrink=0.7)
Out[61]:
<matplotlib.colorbar.Colorbar at 0xac8c898160>
In [62]:
a = np.random.randn(10,10)
plt.imshow(a, interpolation='none', cmap='gray')
plt.colorbar(shrink=0.7)
Out[62]:
<matplotlib.colorbar.Colorbar at 0xac8c6d7f98>
In [63]:
a = np.random.randn(10,10)
plt.imshow(a, cmap='gray')
plt.colorbar(shrink=0.7)
Out[63]:
<matplotlib.colorbar.Colorbar at 0xac8a888438>
In [64]:
a = [[(x-30)**2 + (y-10)**2 for x in range(100)] for y in range(100)] # x값과 y값을 0~99까지 식을 돌림. 100x100의 원소 1만개 2차원행렬
plt.imshow(a, origin='lower')
plt.colorbar()  # z축이라 볼 수 있다.
Out[64]:
<matplotlib.colorbar.Colorbar at 0xac8c6b2080>
In [65]:
a = [[(x)**2 + (y)**2 for x in range(3)] for y in range(3)] 
a
Out[65]:
[[0, 1, 4], [1, 2, 5], [4, 5, 8]]
In [66]:
a = [[(x)**2 + (y)**2 for x in range(3)] for y in range(3)] 
np.array(a)
Out[66]:
array([[0, 1, 4],
       [1, 2, 5],
       [4, 5, 8]])
In [67]:
plt.imshow(a, origin='lower', cmap='gray_r')
plt.colorbar()
Out[67]:
<matplotlib.colorbar.Colorbar at 0xac8c755400>
In [68]:
x = np.arange(-1,1,0.1)
y = np.arange(-1,1,0.1)

xx, yy = np.meshgrid(x,y) # 2차원 등고선 함수를 그릴때 사용

a = np.sin(xx*yy)
plt.imshow(a, origin='lower')
plt.colorbar()
Out[68]:
<matplotlib.colorbar.Colorbar at 0xac8c9acc88>
In [69]:
x = np.arange(-1,1,0.1)
y = np.arange(-1,1,0.1)

xx, yy = np.meshgrid(x,y)
xx.shape, yy.shape # [-1, -0.9,...,0.9]까지 20개의 원소를 가진 똑같은 리스트가 20개 모여서 xx와 yy를 만든다.(교차시키려고?)
Out[69]:
((20, 20), (20, 20))
In [70]:
# 공간에 선을 그어 그  사이사이에 확률값을 준다.
In [71]:
import matplotlib.image as mpimg

img=mpimg.imread('lucy.jpg')
display(img.shape)

# 367x560 이미지 3개가 합성된 이미지 
(367, 560, 3)
In [72]:
plt.imshow(img)
Out[72]:
<matplotlib.image.AxesImage at 0xac8cb68d30>
In [73]:
plt.imshow(img[:,:,0], vmin=0, vmax=255, cmap='Reds_r')  # 보기 좋게 하려고 일부러 cmap을 red계열로 바꿨다. 원래 이렇게 안나옴.
Out[73]:
<matplotlib.image.AxesImage at 0xac8cad4cf8>
In [74]:
plt.imshow(img[:,:,1], vmin=0, vmax=255, cmap='Greens_r')
Out[74]:
<matplotlib.image.AxesImage at 0xac8cb33780>
In [75]:
plt.imshow(img[:,:,2], vmin=0, vmax=255, cmap='Blues_r')
Out[75]:
<matplotlib.image.AxesImage at 0xac8cc051d0>

등고선

  • 이차원 평면 상에서 등고선을 그린다.
In [76]:
x = np.arange(-1,1,0.1)
y = np.arange(-1,1,0.1)

xx, yy = np.meshgrid(x,y)

a = np.sin(xx*yy)
CS = plt.contour(xx, yy, a, levels=np.arange(-1,1,0.2)) # levels는 등고선 간의 간격을 준다.

# plt.contour(a), 같은 값들끼리 연결시켜 등고선을 그린다.
# imshow, contour, contourf 3종류

plt.clabel(CS, inline=2, fontsize=10)
plt.colorbar()
Out[76]:
<matplotlib.colorbar.Colorbar at 0xac8ccb0be0>
In [145]:
x = np.arange(-1,1,0.1)
y = np.arange(-1,1,0.1)

xx, yy = np.meshgrid(x,y)

a = np.sin(xx*yy)
plt.contourf(xx, yy, a) # 색으로서 구분
plt.colorbar()
Out[145]:
<matplotlib.colorbar.Colorbar at 0xf7b078fb38>

cmap

여러개의 플롯을 한번에 그리기 (자주씀)

In [151]:
(fig, axes) = plt.subplots(2,2, figsize=[10,8]) 
# 판을 가로 2개 세로 2개로 만들어 놓겠다. subplot's' 복수형. axes는 array값. 각 판 크기가 10x8이다.
display(axes.shape)

axes[0,0].plot([1,2,3,4])  # 2x2 중 (0,0)에 그래프를 그리겠다.
axes[0,1].scatter(np.random.randn(100), np.random.randn(100))
axes[1,0].bar(range(10),range(10))
axes[1,1].imshow(np.random.randn(64,64))

fig.suptitle('TEST', fontsize=20) # fig에 전체 타이틀 super title
axes[0,0].set_title('TEST1') # 각 그림에 터틀.
(2, 2)
Out[151]:
Text(0.5,1,'TEST1')
In [163]:
fig, axes = plt.subplots(2,2, figsize=[8,10])  
In [172]:
axes = plt.subplots(2,2, figsize=[10,8])  
In [176]:
type(axes)
# 함수는 리턴을 하나만 해줄수 있으므로 튜플을 이용해 2개의 값을 넘긴다. 튜플이 뭐가 넘어오는지 모르면 type이나 len, shape 등등을 이용해 함수를 분석해야해. 
Out[176]:
tuple
In [174]:
axes[0] 
Out[174]:
In [175]:
axes[1]
Out[175]:
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x000000F7B36553C8>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000000F7B393D710>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x000000F7B3964E10>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000000F7B3995470>]],
      dtype=object)
In [77]:
#메인타이틀과 그림 크기 지정하기 위해, 없어도 상관x
fig = plt.figure(figsize=[10,8])
fig.suptitle('TEST', fontsize=20) 

plt.subplot(2,2,1) # 그림을 그릴때마다 좌표를 준다. subplot 단수, 복사붙여넣기에 좋다. 1부터 시작이다.
plt.title('TEST1') 
plt.plot([0,1,2,3]) 

plt.subplot(2,2,2) # 2x2의 2번째 위치에 그림을 그리겠다. for문을 이용해서 표현 가능.
plt.title('TEST2')
plt.scatter(np.random.randn(100), np.random.randn(100))

plt.subplot(2,2,3)
plt.title('TEST3')
plt.bar(range(10),range(10))

plt.subplot(2,2,4)
plt.title('TEST4')
plt.imshow(np.random.randn(64,64))
plt.colorbar()
Out[77]:
<matplotlib.colorbar.Colorbar at 0xac8d4304a8>

for i in range(4):
---- plt.subplot(2,2,i+1)
---- plt.plot(iris[:,i])

  • 오랫만에 구구단

I = []
for i in range(2,10):
----for j in range(1,10):
--------m=[i,j,i*j]
--------I.append(m)

I=[[i,j,i*j] for i in range (2,10) for j in range (1,10)]

텍스트와 화살표 그리기

In [79]:
plt.axis([-10,10,-10,10])   # axis 함수는 x축과 y축의 범위값을 정한다.
plt.vlines([0,5,-5],-10,10,linestyles=':')   # 수평, 수직선을 그린다. vline's' 복수라서 여러개 그린다.
plt.hlines([0,5,-5],-10,10,linestyles=':')

plt.text(0,0,'안녕하세요',fontproperties=prop,fontsize=20,va='center',ha='center') # va수직정렬방법 ha수평정렬방법
plt.annotate('원점',xy=(0,0),xytext=(5,5),arrowprops=dict(facecolor='black'),fontproperties=prop)
# annotate는 화살표를 그리면서 글씨까지 넣을수 있다. 화살방향은 (0,0) 끝방향은 (5,5), arrowprops: 화살방향 모양은 무엇으로 할 것인지.
Out[79]:
Text(5,5,'원점')

플롯을 파일로 저장

In [82]:
x = np.arange(-1,1,0.1)
y = np.arange(-1,1,0.1)

xx, yy = np.meshgrid(x,y)

a = np.sin(xx*yy)
plt.imshow(a, origin='lower')
plt.colorbar()

plt.savefig('myplot.jpg',dpi=200)  
#dpi : dot per inch 1인치에 점을 몇개 넣을것인가.(해상도)
#savefig 플롯을 파일로 폴더에 저장한다.
# 그림에 있는 0~20까지 있는 숫자는 점들의 인덱스를 말한다.
In [94]:
x = np.arange(-1,1,0.1)
y = np.arange(-1,1,0.1)

xx, yy = np.meshgrid(x,y)

a = np.sin(xx*yy)
plt.imshow(a, origin='lower') # origin은 왼쪽 위를 원점으로 잡고 그래프를 그린다.
plt.colorbar()
plt.xticks(range(20), x, rotation=90)

plt.savefig('myplot.jpg',dpi=200)  
In [84]:
plt.plot(np.random.randn(100))
plt.savefig('myplot2.jpg',dpi=100) 
In [86]:
import matplotlib.image as mpimg

img = mpimg.imread('myplot2.jpg')
plt.imshow(img)
plt.axis('off') # 좌표 축을 지워준다.
Out[86]:
(-0.5, 599.5, 399.5, -0.5)

fig = plt.figure()
help(fig)

3차원 그림 맛보기

In [99]:
from mpl_toolkits.mplot3d import Axes3D, axes3d

fig = plt.figure()   #그림판 틀이 figure, 그림판 틀 안에 그림들어가는 부분이 plot이다.
#ax=Axes3D(fig, elev=-152, azim=-26)
ax = Axes3D(fig)

rng = np.arange(-10,10,0.5)
X,Y = np.meshgrid(rng, rng)
Z = 1 / (1+np.exp(-1*(X+Y)))

m = ax.scatter(X,Y,Z, s=5, cmap='autumn')

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
Out[99]:
Text(0.5,0,'Z')

'beginner > 파이썬 기초' 카테고리의 다른 글

스택(stack)&큐(Queue)기본개념  (0) 2019.04.09
장바구니 알고리즘  (0) 2019.03.05
NumPy_기타  (0) 2019.02.19
NumPy_구간나누기  (0) 2019.02.18
NumPy_정렬  (0) 2019.02.15
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함