Matplotlib 을 사용한 화살표 플롯팅

Beginner

This tutorial is from open-source community. Access the source code

소개

Matplotlib 는 Python 에서 강력한 플로팅 라이브러리입니다. 선 그래프, 산점도, 막대 그래프, 히스토그램 등 다양한 사용자 정의 시각화를 제공합니다. Matplotlib 가 제공하는 시각화 중 하나는 화살표 플롯입니다. 화살표 플롯은 화살표 길이, 너비 또는 알파 (투명도) 를 사용하여 마르코프 모델의 전이 확률과 같은 화살표 "강도"를 인코딩하는 데 사용됩니다.

이 랩에서는 Matplotlib 를 사용하여 화살표 플롯을 만드는 방법을 배웁니다. make_arrow_graph() 함수를 사용하여 화살표 그래프를 플롯합니다.

VM 팁

VM 시작이 완료되면 왼쪽 상단을 클릭하여 Notebook 탭으로 전환하여 실습을 위해 Jupyter Notebook에 액세스하십시오.

때로는 Jupyter Notebook 이 로딩을 완료하는 데 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한으로 인해 작업의 유효성 검사는 자동화할 수 없습니다.

학습 중 문제가 발생하면 언제든지 Labby 에게 문의하십시오. 세션 후 피드백을 제공해주시면 문제를 즉시 해결해 드리겠습니다.

라이브러리 가져오기 및 함수 정의

첫 번째 단계는 필요한 라이브러리를 가져오고 make_arrow_graph() 함수를 정의하는 것입니다. 이 함수는 축 (axes), 데이터, 크기, 표시, 모양, max_arrow_width, arrow_sep, alpha, normalize_data, ec, labelcolor 및 kwargs 와 같은 다양한 매개변수를 입력으로 받습니다. 이 매개변수를 사용하여 화살표 플롯을 생성합니다.

## Import libraries
import itertools
import matplotlib.pyplot as plt
import numpy as np

## Define the function
def make_arrow_graph(ax, data, size=4, display='length', shape='right',
                     max_arrow_width=0.03, arrow_sep=0.02, alpha=0.5,
                     normalize_data=False, ec=None, labelcolor=None,
                     **kwargs):
    """
    Makes an arrow plot.

    Parameters
    ----------
    ax
        The axes where the graph is drawn.
    data
        Dict with probabilities for the bases and pair transitions.
    size
        Size of the plot, in inches.
    display : {'length', 'width', 'alpha'}
        The arrow property to change.
    shape : {'full', 'left', 'right'}
        For full or half arrows.
    max_arrow_width : float
        Maximum width of an arrow, in data coordinates.
    arrow_sep : float
        Separation between arrows in a pair, in data coordinates.
    alpha : float
        Maximum opacity of arrows.
    **kwargs
        `.FancyArrow` properties, e.g. *linewidth* or *edgecolor*.
    """

    ## code block

데이터 정의 및 화살표 그래프 플롯

두 번째 단계는 데이터를 정의하고 make_arrow_graph() 함수를 사용하여 화살표 그래프를 플롯하는 것입니다. 우리는 데이터를 염기 및 쌍 전이에 대한 확률을 포함하는 딕셔너리로 정의합니다. 또한 플롯의 크기를 4 로 설정하고 데이터를 정규화합니다.

## Define the data
data = {
    'A': 0.4, 'T': 0.3, 'G': 0.6, 'C': 0.2,
    'AT': 0.4, 'AC': 0.3, 'AG': 0.2,
    'TA': 0.2, 'TC': 0.3, 'TG': 0.4,
    'CT': 0.2, 'CG': 0.3, 'CA': 0.2,
    'GA': 0.1, 'GT': 0.4, 'GC': 0.1,
}

## Plot the arrow graph
size = 4
fig = plt.figure(figsize=(3 * size, size), layout="constrained")
axs = fig.subplot_mosaic([["length", "width", "alpha"]])

for display, ax in axs.items():
    make_arrow_graph(
        ax, data, display=display, linewidth=0.001, edgecolor=None,
        normalize_data=True, size=size)

plt.show()

화살표 그래프 사용자 정의

세 번째 단계는 화살표 그래프를 사용자 정의하는 것입니다. display 매개변수를 사용하여 표시할 화살표 속성을 변경할 수 있습니다. 또한 shape 매개변수를 사용하여 화살표의 모양을 변경할 수 있습니다. max_arrow_widtharrow_sep 매개변수를 사용하여 화살표의 너비와 간격을 각각 조정할 수 있습니다. alpha 매개변수를 사용하여 화살표의 투명도를 변경할 수 있습니다. 또한 labelcolor 매개변수를 사용하여 레이블의 색상을 변경할 수 있습니다.

## Plot the arrow graph with customizations
size = 4
fig = plt.figure(figsize=(3 * size, size), layout="constrained")
axs = fig.subplot_mosaic([["length", "width", "alpha"]])

for display, ax in axs.items():
    make_arrow_graph(
        ax, data, display=display, linewidth=0.001, edgecolor=None,
        normalize_data=True, size=size, shape='full', max_arrow_width=0.05,
        arrow_sep=0.03, alpha=0.7, labelcolor='white')

plt.show()

화살표 그래프 해석

네 번째 단계는 화살표 그래프를 해석하는 것입니다. 화살표의 길이, 너비 및 불투명도는 화살표 강도를 나타냅니다. 화살표 그래프는 화살표 길이, 너비 또는 알파 (불투명도) 를 사용하여 마르코프 모델 (Markov model) 의 전이 확률과 같은 화살표 "강도"를 인코딩하는 데 사용할 수 있습니다. 화살표의 레이블은 염기 및 쌍 전이에 대한 확률을 나타냅니다.

요약

이 랩에서는 Matplotlib 을 사용하여 화살표 플롯을 만드는 방법을 배웠습니다. make_arrow_graph() 함수를 사용하여 화살표 그래프를 그렸습니다. 표시할 화살표 속성을 변경하고, 화살표 모양을 변경하고, 화살표의 너비와 간격을 조정하고, 화살표의 투명도를 변경하고, 레이블의 색상을 변경하여 화살표 그래프를 사용자 정의했습니다. 또한 화살표의 길이, 너비 및 불투명도가 화살표 강도를 나타내고, 화살표의 레이블이 염기 및 쌍 전이에 대한 확률을 나타낸다는 것을 이해함으로써 화살표 그래프를 해석했습니다.