Python Matplotlib 을 이용한 타원 그리기

Beginner

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

소개

이 랩에서는 Python Matplotlib 를 사용하여 타원을 그리는 방법을 보여줍니다. 이 랩은 두 가지 예제를 다룹니다.

  • 개별 타원 그리기
  • 서로 다른 각도의 타원 그리기

    연습을 시작하려면 WebIDE 에서 ellipse-demo.ipynb를 여십시오. VS Code 에서 Jupyter Notebook 사용 방법을 알아보세요.
    Matplotlib ellipse drawing example
    Labby 는 노트북에 접근할 수 없으므로 정답을 자동으로 확인할 수 없습니다.

필요한 라이브러리 가져오기

먼저, 필요한 라이브러리를 가져와야 합니다. numpy를 사용하여 임의의 데이터를 생성하고, matplotlib.pyplotmatplotlib.patches를 사용하여 타원을 그립니다.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse

개별 타원 그리기

이 예제에서는 임의의 크기, 위치 및 색상을 가진 여러 타원을 그립니다. 각 타원은 Ellipse 클래스의 인스턴스가 됩니다.

## 재현성을 위해 난수 상태 고정
np.random.seed(19680801)

## 그릴 타원의 수
NUM = 250

## 타원 생성
ells = [Ellipse(xy=np.random.rand(2) * 10,
                width=np.random.rand(), height=np.random.rand(),
                angle=np.random.rand() * 360)
        for i in range(NUM)]

## 플롯을 생성하고 종횡비를 'equal'로 설정
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})

## 각 타원을 플롯에 추가
for e in ells:
    ax.add_artist(e)
    e.set_clip_box(ax.bbox)
    e.set_alpha(np.random.rand())
    e.set_facecolor(np.random.rand(3))

## 플롯의 x 및 y 제한 설정
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)

## 플롯 표시
plt.show()

다양한 각도로 타원 그리기

이 예제에서는 다양한 각도를 가진 여러 타원을 그립니다. 루프를 사용하여 그리고자 하는 각도별로 Ellipse 인스턴스를 생성합니다.

## 각도 단계 및 그릴 각도 범위 정의
angle_step = 45  ## degrees
angles = np.arange(0, 180, angle_step)

## 플롯을 생성하고 종횡비를 'equal'로 설정
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})

## 각도에 대해 반복하고 각 각도에 대해 타원을 그립니다.
for angle in angles:
    ellipse = Ellipse((0, 0), 4, 2, angle=angle, alpha=0.1)
    ax.add_artist(ellipse)

## 플롯의 x 및 y 제한 설정
ax.set_xlim(-2.2, 2.2)
ax.set_ylim(-2.2, 2.2)

## 플롯 표시
plt.show()

요약

이 랩에서는 Python Matplotlib 을 사용하여 타원을 그리는 방법을 배웠습니다. 개별 타원 그리기와 다양한 각도를 가진 타원 그리기, 두 가지 예제를 다루었습니다. 이 랩의 단계를 따르면 Matplotlib 을 사용하여 자신만의 Python 프로젝트에서 타원을 그릴 수 있습니다.