AI/이론

matplotlib I

N-analyst 2021. 1. 29. 19:30
matplotlib I

Matpltlib I


matplotlib

matplotlib는 많은 함수와 인자가 있어서 document확인해 본다. https://matplotlib.org/3.1.1/tutorials/introductory/pyplot.html

  • pyplot객체를 사용하여 데이터를 표시
  • pyplot객체에 그래프들을 쌓은 다음 flush
In [1]:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
In [2]:
X=range(100)
Y=[val**2 for val in X]
plt.plot(X,Y)
plt.show()

image.png

  • 최대 단점 argumnet를 kwargs받음
  • 고정된 argument가 없어서 alt+tab으로 확인이 어려움
In [3]:
X_1=range(100)
Y_1=[np.cos(val) for val in X_1]

X_2=range(100)
Y_2=[np.sin(val) for val in X_2]

plt.plot(X_1,Y_1)
plt.plot(X_2,Y_2)
plt.show()
  • Graph는 원래 figure객체에 생성됨
  • pyplot객체 사용시, 기본 figure에 그래프가 그려짐



Figure & Axes

  • Matplotlib는 Figure안에 Axes로 구성
  • Figure위에 여러 개의 Axes를 생성 image.png
In [4]:
fig = plt.figure()  # figure 반환
fig.set_size_inches(10, 10)  # 크기지정

ax_1 = fig.add_subplot(2, 2, 1)  # 두개의 plot 생성
ax_2 = fig.add_subplot(2, 2, 2)  # 두개의 plot 생성
ax_3 = fig.add_subplot(2, 1, 2)  # 두개의 plot 생성

ax_1.plot(X_1, Y_1, c="b")  # 첫번째 plot
ax_2.plot(X_2, Y_2, c="g")  # 두번째 plot
ax_3.plot(X_1, Y_1)
plt.show()  # show & flush


subplots

  • Subplot의 순서를 grid로 작성 image.png
In [5]:
fig = plt.figure()
fig.set_size_inches(10, 8)  # size 설정
# plt.style.use("ggplot")    # 스타일적용

ax = []
colors = ["b", "g", "r", "c", "m", "y", "k"]
for i in range(1, 7):
    ax.append(fig.add_subplot(2, 3, i))  # 두개의 plot 생성
    X_1 = np.arange(50)
    Y_1 = np.random.rand(50)
    c = colors[np.random.randint(1, len(colors))]

    ax[i - 1].plot(X_1, Y_1, c=c)


set color

In [6]:
X=np.arange(100)
Y=X**2

X_1=X
Y_1=Y+2000

plt.plot(X,Y,color='#eeefff')
plt.plot(X_1,Y_1,color='r')
Out[6]:
[<matplotlib.lines.Line2D at 0x2073a058288>]


set linestyle

  • ls 또는 linestyle속성 사용
In [7]:
plt.plot(X,Y,c='b',linestyle='dashed')
plt.plot(X_1,Y_1,color='r',ls='dotted')
Out[7]:
[<matplotlib.lines.Line2D at 0x20739eca388>]


set title

  • pyplot에 title함수 사용, figure의 subplot별로 입력가능
  • latex타입의 표혀노 가능(수식 표현 가능)
In [8]:
plt.plot(X,Y,c='b',linestyle='dashed')
plt.plot(X_1,Y_1,color='r',ls='dotted')

#### set title####
plt.title('Two curves')
Out[8]:
Text(0.5, 1.0, 'Two curves')
In [9]:
plt.plot(X,Y,c='b',linestyle='dashed')
plt.plot(X_1,Y_1,color='r',ls='dotted')

#### set title####
plt.title("$y = ax^{2} + b$")
plt.show()


set legend

  • legend함수로 범례를 표시함, loc위치등 속성 지정
In [10]:
plt.plot(X,Y,c='b',linestyle='dashed',label='curve_1')
plt.plot(X_1,Y_1,color='r',ls='dotted',label='curve_2')

#### set legend ####
plt.legend(shadow=True,fancybox=True,loc='lower right')
Out[10]:
<matplotlib.legend.Legend at 0x2073b1aefc8>


set grid & xylim

In [11]:
plt.plot(X,Y,c='b',linestyle='dashed',label='curve_1')
plt.plot(X_1,Y_1,color='r',ls='dotted',label='curve_2')

#### set title####
plt.title("$y = ax^{2} + b$")

#### set legend ####
plt.legend(shadow=True,fancybox=True,loc='lower right')

#### set grid & xylim ####
plt.grid(True, lw=0.4, ls="--", c=".90")
plt.xlim(-100, 200)
plt.ylim(0, 4000)
Out[11]:
(0.0, 4000.0)
In [12]:
plt.style.use('ggplot')
In [13]:
plt.plot(X,Y,c='b',linestyle='dashed',label='curve_1')
plt.plot(X_1,Y_1,color='r',ls='dotted',label='curve_2')

#### set title####
plt.title("$y = ax^{2} + b$")

#### set legend ####
plt.legend(shadow=True,fancybox=True,loc='lower right')

#### set grid & xylim ####
plt.xlim(-100, 200)
plt.ylim(0, 4000)
Out[13]:
(0.0, 4000.0)


annotate & text

  • text: 그래프 위에 글을 적는다.
  • annotate: 글도 적고 화살표도 나타낼 수 있다.
In [14]:
plt.style.use('default')
In [15]:
plt.plot(X,Y,c='b',linestyle='dashed',label='curve_1')
plt.plot(X_1,Y_1,color='r',ls='dotted',label='curve_2')


#### set text & annotate ####
plt.text(50, 1600, "curve_1")
plt.annotate(
    "curve_2",
    xy=(30, 2900),       # 화살표 끝점
    xytext=(-25, 3000),   # text도 나타내고 화살표의 시작점
    arrowprops=dict(facecolor="black", shrink=0.05))


#### set title####
plt.title("$y = ax^{2} + b$")

#### set legend ####
plt.legend(shadow=True,fancybox=True,loc='lower right')

#### set grid & xylim ####
plt.xlim(-100, 200)
plt.ylim(0, 4000)
Out[15]:
(0.0, 4000.0)


set label

  • x,y축의 글을 쓸 수 있다.
In [16]:
fig = plt.figure()  # figure 반환
fig.set_size_inches(5, 3)  # 크기지정

plt.plot(X,Y,c='b',linestyle='dashed',label='curve_1')
plt.plot(X_1,Y_1,color='r',ls='dotted',label='curve_2')

#### set title####
plt.title("$y = ax^{2} + b$")

#### set legend ####
plt.legend(shadow=True,fancybox=True,loc='lower right')

#### set grid & xylim ####
plt.grid(True, lw=0.4, ls="--", c=".90")
plt.xlim(-100, 200)
plt.ylim(0, 4000)

#### set label ####
plt.xlabel("x_line")
plt.ylabel("y_line")
Out[16]:
Text(0, 0.5, 'y_line')


save

  • savefig함수를 통해서 그래프를 이미지로 저장할 수 있다.
In [17]:
plt.plot(X,Y,c='b',linestyle='dashed')
plt.plot(X_1,Y_1,color='r',ls='dotted')

#### set title####
plt.title("$y = ax^{2} + b$")

#### save ####
plt.savefig('test.png')



예시

In [18]:
df = pd.read_csv("./data/phone_data.csv")
df.head()
Out[18]:
index date duration item month network network_type
0 0 15/10/14 06:58 34.429 data 2014-11 data data
1 1 15/10/14 06:58 13.000 call 2014-11 Vodafone mobile
2 2 15/10/14 14:46 23.000 call 2014-11 Meteor mobile
3 3 15/10/14 14:48 4.000 call 2014-11 Tesco mobile
4 4 15/10/14 17:27 4.000 call 2014-11 Tesco mobile

월별 통화량 데이터 총합

In [19]:
result = df.groupby(["month"])["duration"].sum()
result
Out[19]:
month
2014-11    26639.441
2014-12    14641.870
2015-01    18223.299
2015-02    15522.299
2015-03    22750.441
Name: duration, dtype: float64
In [20]:
fig = plt.figure(figsize=(5,3))  # figure 반환

plt.plot(result.index, result, color="b", linestyle="dashed")

plt.title("Durations per month")
plt.show()


일별 네트워크별 데이터의 총량을 다중 plot으로 작성

In [21]:
df["day"]=df["date"].str[:9]
df.head()
Out[21]:
index date duration item month network network_type day
0 0 15/10/14 06:58 34.429 data 2014-11 data data 15/10/14
1 1 15/10/14 06:58 13.000 call 2014-11 Vodafone mobile 15/10/14
2 2 15/10/14 14:46 23.000 call 2014-11 Meteor mobile 15/10/14
3 3 15/10/14 14:48 4.000 call 2014-11 Tesco mobile 15/10/14
4 4 15/10/14 17:27 4.000 call 2014-11 Tesco mobile 15/10/14
In [22]:
result=df.groupby(["network", "day"])["duration"].sum().reset_index()
result.head()
Out[22]:
network day duration
0 Meteor 01/03/15 9.0
1 Meteor 02/01/15 2.0
2 Meteor 02/03/15 192.0
3 Meteor 02/11/14 177.0
4 Meteor 02/12/14 526.0
In [23]:
result["network"].unique().tolist()
Out[23]:
['Meteor',
 'Tesco',
 'Three',
 'Vodafone',
 'data',
 'landline',
 'special',
 'voicemail',
 'world']
In [24]:
result[result["network"] == "data"].head()
Out[24]:
network day duration
256 data 01/01/15 34.429
257 data 01/02/15 34.429
258 data 01/03/15 34.429
259 data 01/11/14 34.429
260 data 01/12/14 34.429
In [25]:
fig = plt.figure()
fig.set_size_inches(12, 10)  # size 설정

network_types = result["network"].unique().tolist()
ax = []
for i in range(1, 7):
    ax.append(fig.add_subplot(2, 3, i))  # 두개의 plot 생성
    network_name = network_types[i - 1]

    plt.title(network_name)

    X_1 = result[result["network"] == network_name]["day"]
    Y_1 = result[result["network"] == network_name]["duration"]
    ax[i - 1].get_xaxis().set_visible(False)
    ax[i - 1].plot(X_1, Y_1)
  • get_xaxis().set_visible(False)의 설정을 통해서 x축의 값을 안보이게 한다.