상세 컨텐츠

본문 제목

Matplotlib을 사용하여 관계대명사와 수동태의 영작과정 시각화하기

Python 기초학습

by 달의 언어 2023. 7. 24. 19:51

본문

 Matplotlib는 Python에서 사용하는 강력한 시각화 라이브러리입니다. 

간단한 선 그래프에서부터 복잡한 3차원 그래프까지 그릴 수 있으며, 

이러한 그래프를 사용하여 데이터를 더욱 잘 이해하고 설명할 수 있습니다.

Matplotlib는 다음과 같은 주요 기능을 제공합니다:

라인 플롯: 선 그래프는 시간의 변화에 따른 특정 값을 추적하는 데 유용합니다. 

예를 들어, 주식 가격의 변동, 기온의 변화 등을 나타낼 수 있습니다.

바 차트: 바 차트는 카테고리별로 값을 비교하는 데 유용합니다. 

예를 들어, 다양한 제품의 판매량, 학교의 과목별 성적 등을 비교할 수 있습니다.

히스토그램: 히스토그램은 데이터의 분포를 시각화하는 데 사용됩니다. 

예를 들어, 시험 점수의 분포, 제품의 크기 분포 등을 나타낼 수 있습니다.

스캐터 플롯: 스캐터 플롯은 두 변수 간의 관계를 나타내는 데 사용됩니다. 

예를 들어, 키와 몸무게, 연간 수입과 소비 등의 관계를 나타낼 수 있습니다.

파이 차트: 파이 차트는 전체 중 각 부분의 비율을 나타내는 데 사용됩니다. 

예를 들어, 예산의 분배, 선거 결과 등을 나타낼 수 있습니다.

Matplotlib을 설치하기 위해서는 다음의 명령어가 필요합니다.

pip install matplotlib

 

colab에서 matplotlib 라이브러리를 설치하였습니다.

 

잘 설치되었는지를 확인하기 위해서 다음의 코드를 입력해서 그래프가 나오는지 확인하였습니다. 

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 200)
y = np.sin(x)

fig, ax = plt.subplots()
ax.plot(x, y)
plt.show()

 

설치가 잘되었는지 확인하기 위해서 코드를 실행하였습니다.
잘 설치된 것 같습니다.

 

 Matplotlib을 사용하여 관계대명사와 수동태의 영작과정 시각화하기

저는 이 도구를 영어문장 학습에 도움이 될 수 있도록 사용할 방법을 찾고 있습니다.

ChatGPT에게 질문을 던졌습니다. 

나: I want to use matplotlib to visualize the process of sentence merging in English grammar.
(matplotlib를 사용하여 영어 문법에서 문장이 병합되는 과정을 시각화하고 싶습니다.)

The girl is my sister.  The girl who is short is my sister. I want to show the students the process of 'she' became 'who' and two sentences into one sentence using relative pronouns.  or I want to show them how 'he stole my car.' becomes 'my car was stolen by him.' using passive voice. I want the kids to see clearly the step by step in visualization. 

(A) The girl is my sister.

(B) She is short.

(C) The girl who is short is my sister. 

(A)와 (B)의 두 문장이 관계대명사를 이용해 한 문장으로 바뀌는 과정과

(D) He stole my car.

(E) My car was stolen by him.

(D)의 능동태 문장이 (E)의 수동태 문장으로 바뀌는 과정을 시각화하고 싶다고 요청하였습니다.

다음은 ChatGPT의 답변입니다. 

그래프를 생성하는 matplotlib의 networkx 라이브러리를 사용하여 플로우차트와 같은 시각화를 만들 수 있습니다. 첫 번째 예를 살펴봅시다:
"그 소녀는 내 여동생이다."
"그녀는 키가 작다."
"키가 작은 소녀는 내 여동생이다."
이 변환은 노드와 가장자리로 나타낼 수 있는데,
각 노드는 문장 또는 중요한 변환 단계이고
각 가장자리는 연산입니다(예: "she"를 "who"로 바꾸는 것). 
import matplotlib.pyplot as plt
import networkx as nx

def plot_sentence_transformation(edges, title):
    G = nx.DiGraph()
    G.add_edges_from(edges)

    pos = nx.spring_layout(G)
    plt.figure(figsize=(8,6))

    nx.draw_networkx_nodes(G, pos, node_color='skyblue', node_size=2000)
    nx.draw_networkx_edges(G, pos, edge_color='gray', arrowstyle='-|>', arrowsize=20)
    nx.draw_networkx_labels(G, pos, font_size=12)

    plt.title(title)
    plt.axis('off')
    plt.show()


# Example 1
edges_1 = [
    ("The girl is my sister.", "Replace 'she' with 'who'"),
    ("She is short.", "Replace 'she' with 'who'"),
    ("Replace 'she' with 'who'", "The girl who is short is my sister.")
]
plot_sentence_transformation(edges_1, "Transformation using relative pronouns")

# Example 2
edges_2 = [
    ("He stole my car.", "Change active voice to passive voice"),
    ("Change active voice to passive voice", "My car was stolen by him.")
]
plot_sentence_transformation(edges_2, "Transformation from active to passive voice")

코드인터프리터에서 한참을 기다려도 이미지가 나오지 않아서 

Colab에서 코드를 실행시켰습니다. 

코드인터프리터가 반환한 다이어그램

 

두 문장의 the girl과 she의 공통관계를 찾고, she를 who로 대체한 다음, 두 문장을 하나로 합치는 과정을 다이어그램으로 잘 나타내주었습니다. 

다이어그램이 너무 밋밋해서, 조금 더 시각화에 힘을 써달라고 요청하였습니다. 


나: I want to elaborate the code more visually detailed. 

(코드를 좀 더 시각적으로 자세히 설명하고 싶습니다. )

ChatGPT가 반환한 코드는 다음과 같습니다. 

def plot_detailed_transformation(edges, node_colors, title):
    G = nx.DiGraph()
    G.add_edges_from(edges)

    pos = nx.spring_layout(G, seed=42)  # Fixed layout for consistent graph
    plt.figure(figsize=(10,8))

    # Draw nodes with different colors based on type
    nx.draw_networkx_nodes(G, pos, node_color=[node_colors[n] for n in G.nodes], node_size=2000)
    
    # Draw edges with labels
    nx.draw_networkx_edges(G, pos, edge_color='gray', arrowstyle='-|>', arrowsize=20)
    edge_labels = nx.get_edge_attributes(G, 'label')
    nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=10)
    
    nx.draw_networkx_labels(G, pos, font_size=12)

    plt.title(title)
    plt.axis('off')
    plt.show()


# Detailed example
edges = [
    ("The girl is my sister.", "Identify common noun", {"label": "Step 1"}),
    ("She is short.", "Identify common noun", {"label": "Step 1"}),
    ("Identify common noun", "Replace 'she' with 'who'", {"label": "Step 2"}),
    ("Replace 'she' with 'who'", "Merge sentences", {"label": "Step 3"}),
    ("Merge sentences", "The girl who is short is my sister.", {"label": "Step 4"}),
]
node_colors = {
    "The girl is my sister.": "skyblue",
    "She is short.": "skyblue",
    "Identify common noun": "yellow",
    "Replace 'she' with 'who'": "yellow",
    "Merge sentences": "yellow",
    "The girl who is short is my sister.": "green",
}
plot_detailed_transformation(edges, node_colors, "Detailed Transformation using Relative Pronouns")


시각화를 더 진행하기 위해서 고려할 것은 다음과 같습니다. 


중간 단계를 더 추가합니다: 강조하고 싶은 문장 변환과 관련된 단계가 더 있는 경우, 이러한 단계에 대해 그래프에 노드를 더 추가할 수 있습니다.

색상과 도형 사용: 노드 유형(예: 원본 문장, 변형된 문장, 연산)에 따라 다른 색상을 사용할 수 있으며, 노드 유형에 따라 다른 모양도 사용할 수 있습니다.

가장자리에 레이블을 추가합니다: 가장자리에 레이블을 추가하여 각 가장자리가 어떤 연산을 나타내는지 명확하게 표시할 수 있습니다.

레이아웃 조정: 가독성을 높이기 위해 그래프의 레이아웃을 조정할 수 있습니다. 예를 들어, 노드를 계층 구조로 정렬하여 변환 단계의 순서를 명확하게 보여줄 수 있습니다.

수동태 문장도 같은 방식으로 코드를 짜달라고 요청하였고 ChatGPT 코드인터프리터가 반환한 코드는 다음과 같습니다. 

def plot_detailed_transformation_top_down_fixed(edges, node_colors, title):
    G = nx.DiGraph()
    G.add_edges_from(edges)

    # Arrange nodes in layers from top to bottom
    layers = [
        [node for node in G.nodes if node in layer]
        for layer in [["He stole my car."], 
                      ["Identify subject, verb, object"], 
                      ["Rearrange to object-verb-subject"], 
                      ["Change verb to passive form"], 
                      ["My car was stolen by him."]]
    ]
    
    # Assign 'layer' attribute to each node
    for i, layer in enumerate(layers):
        for node in layer:
            G.nodes[node]["layer"] = i

    pos = nx.multipartite_layout(G, subset_key="layer", align='vertical')
    for i, layer in enumerate(layers):
        for node in layer:
            pos[node][1] = len(layers) - i  # Reverse the y-coordinates to make the graph top-down

    plt.figure(figsize=(10,8))

    # Draw nodes with different colors based on type
    nx.draw_networkx_nodes(G, pos, node_color=[node_colors[n] for n in G.nodes], node_size=2000)
    
    # Draw edges with labels
    nx.draw_networkx_edges(G, pos, edge_color='gray', arrowstyle='-|>', arrowsize=20)
    edge_labels = nx.get_edge_attributes(G, 'label')
    nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=10)
    
    nx.draw_networkx_labels(G, pos, font_size=12)

    plt.title(title)
    plt.axis('off')
    plt.show()

plot_detailed_transformation_top_down_fixed(edges_passive, node_colors_passive, "Detailed Transformation from Active to Passive Voice (Top Down)")

 

수동태를 이용하여 변환하는 과정에서 코드인터프리터의 오류가 더 많이 발생하였습니다. 

마지막에 반환한 코드에도 오류가 있었지만, 

단계별로 step 1 주어, 동사, 목적어를 확인한다.

step 2 목적어, 동사, 주어로 재배열한다. 

step 3 동사를 수동태형태로 바꾼다

step 4 수동태로 바뀐문장. 

 

 

후기

 

수동태 변환 시에 by 뒤에 him이 빠져서 찜찜했습니다. 

그래서 글을 마무리 지으려다 계속 다시 요청했지만, 

라이브러리 설치가 안되어 있어서인지 계속 오류가 났습니다. 

 

 

결국 him을 해결하지는 못했지만,

ChatGPT의 코드인터프리터와 Matplotlib 파이썬 라이브러리의 '힘'을 엿볼 수 있는 좋은 기회였던 것 같습니다. 

 

#데이터시각화기법
#데이터시각화도구
#데이터분석및시각화
#그래프생성
#그래프시각화
#데이터를이용한그래프작성
#파이썬시각화라이브러리
#데이터시각화를위한라이브러리
#베스트시각화라이브러리
#영어문법기초
#영어문법연습
#중학교영어문법교육
#영어문장병합
#문장병합기법
#문장병합을위한영어문법
#관계대명사사용법
#영어문장에서의관계대명사
#관계대명사연습
#영어수동태문법
#수동태와능동태
#수동태문장작성법
#파이썬프로그래밍기초
#파이썬을이용한데이터분석
#파이썬프로그래밍연습

'Python 기초학습' 카테고리의 다른 글

Python 부트캠프 노트필기 (Day 1)  (0) 2023.04.11
2의 보수 구하기  (0) 2023.04.11

관련글 더보기

댓글 영역