강의노트 Plotting을 위한 입력 유형

조회수 67 • 댓글 0 • 수정 5개월 전 크게 보기  
  • Matplotlib
  • matplotlib

입력 유형

Plotting 함수는 numpy.array 또는 numpy.ma.masked_array를 입력으로 받거나 numpy.asarray로 전달할 수 있는 객체이어야 한다. pandas 데이터 객체나 numpy.matrix와 같이 배열과 유사한 클래스는 의도한 대로 작동하지 않을 수 있기때문에 플로팅 전에 numpy.array 객체로 변환해야 한다.

b = np.matrix([[1, 2], [3, 4]])  #b는 matrix 타입의 데이터이다.
b_asarray = np.asarray(b)      #b를 array 타입으로 변환하였다.

딕셔너리, 구조화된 numpy 배열 또는 pandas.DataFrame과 같은 문자열로 색인된 데이터도 Matplotlib에서는 데이터 키워드 인수를 제공하고 x 및 y 변수에 해당하는 문자열을 전달하여 플롯을 생성할 수 있다.

np.random.seed(19680801)  # seed the random number generator.
data = {'a': np.arange(50),
        'c': np.random.randint(0, 50, 50),
        'd': np.random.randn(50)} # 딕셔너리 데이터
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100

fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
ax.scatter('a', 'b', c='c', s='d', data=data) #딕셔너리 데이터인 data의 변수들을 플롯해준다.
ax.set_xlabel('entry a')
ax.set_ylabel('entry b')

코딩 스타일

Explicit(명시적), Implicit(암시적)하게 표현

Explicit방법 : 그림과 축을 만들고 그 위에 메서드를 호출하는 방법이다.

Implicit방법 : pyplot을 사용하여 그림과 축을 암시적으로 생성 및 관리하고 pyplot 함수를 사용하여 플로팅합니다.

# Explicit 방법
x = np.linspace(0, 2, 100)  # Sample data.

# Note that even in the OO-style, we use `.pyplot.figure` to create the Figure.
fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
ax.plot(x, x, label='linear')  # Plot some data on the axes.
ax.plot(x, x**2, label='quadratic')  # Plot more data on the axes...
ax.plot(x, x**3, label='cubic')  # ... and some more.
ax.set_xlabel('x label')  # Add an x-label to the axes.
ax.set_ylabel('y label')  # Add a y-label to the axes.
ax.set_title("Simple Plot")  # Add a title to the axes.
ax.legend()  # Add a legend.

# Implicit 방법
x = np.linspace(0, 2, 100)  # Sample data.

plt.figure(figsize=(5, 2.7), layout='constrained')
plt.plot(x, x, label='linear')  # Plot some data on the (implicit) axes.
plt.plot(x, x**2, label='quadratic')  # etc.
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
plt.legend()

함수로 만들기

동일한 플롯을 다른 데이터로 반복해서 만들어야 할 경우 함수를 사용하는 것을 추천한다.

def my_plotter(ax, data1, data2, param_dict):
    """
    A helper function to make a graph.
    """
    out = ax.plot(data1, data2, **param_dict)
    return out

data1, data2, data3, data4 = np.random.randn(4, 100)  # make 4 random data sets
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(5, 2.7))
my_plotter(ax1, data1, data2, {'marker': 'x'})  # my_plotter함수를 사용하여 그래프를 그린다.
my_plotter(ax2, data3, data4, {'marker': 'o'}) 

Matplotlib는 mpl-cookiecutter에 다양한 템플릿이 준비되어 있다.

이전 글
다음 글
댓글
댓글로 소통하세요.