単位付き楕円

PythonPythonBeginner
今すぐ練習

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

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、Python Matplotlibを使って、円弧で生成された楕円と多角形近似とを比較する方法を学びます。

VMのヒント

VMの起動が完了したら、左上隅をクリックしてノートブックタブに切り替え、Jupyter Notebookを使って練習しましょう。

時々、Jupyter Notebookが読み込み終了するまで数秒待つ必要があります。Jupyter Notebookの制限により、操作の検証は自動化できません。

学習中に問題に遭遇した場合は、Labbyにお問い合わせください。セッション後にフィードバックを提供してください。すぐに問題を解決いたします。

ライブラリのインポート

まず、必要なライブラリをインポートします。

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

楕円のパラメータを設定する

このステップでは、楕円のパラメータを設定します。

xcenter, ycenter = 0.38, 0.52
width, height = 0.1, 0.3
angle = -30

円弧を使って楕円を生成する

このステップでは、円弧を使って楕円を生成します。

theta = np.deg2rad(np.arange(0.0, 360.0, 1.0))
x = 0.5 * width * np.cos(theta)
y = 0.5 * height * np.sin(theta)

rtheta = np.radians(angle)
R = np.array([
    [np.cos(rtheta), -np.sin(rtheta)],
    [np.sin(rtheta),  np.cos(rtheta)],
    ])

x, y = np.dot(R, [x, y])
x += xcenter
y += ycenter

多角形近似を使って楕円を生成する

このステップでは、多角形近似を使って楕円を生成します。

theta = np.deg2rad(np.arange(0.0, 360.0, 1.0))
x = 0.5 * width * np.cos(theta)
y = 0.5 * height * np.sin(theta)

rtheta = np.radians(angle)
R = np.array([
    [np.cos(rtheta), -np.sin(rtheta)],
    [np.sin(rtheta),  np.cos(rtheta)],
    ])

x, y = np.dot(R, [x, y])
x += xcenter
y += ycenter

円弧を使って楕円を描画する

このステップでは、円弧を使って楕円を描画します。

fig = plt.figure()
ax = fig.add_subplot(211, aspect='auto')
ax.fill(x, y, alpha=0.2, facecolor='yellow',
        edgecolor='yellow', linewidth=1, zorder=1)

e1 = patches.Arc((xcenter, ycenter), width, height,
                 angle=angle, linewidth=2, fill=False, zorder=2)

ax.add_patch(e1)

多角形近似を使って楕円を描画する

このステップでは、多角形近似を使って楕円を描画します。

ax = fig.add_subplot(212, aspect='equal')
ax.fill(x, y, alpha=0.2, facecolor='green', edgecolor='green', zorder=1)
e2 = patches.Arc((xcenter, ycenter), width, height,
                 angle=angle, linewidth=2, fill=False, zorder=2)

ax.add_patch(e2)
fig.savefig('arc_compare')

plt.show()

まとめ

この実験では、PythonのMatplotlibを使って、円弧で生成された楕円と多角形近似による楕円を比較する方法を学びました。楕円のパラメータを設定する方法、円弧と多角形近似を使って楕円を生成する方法、およびMatplotlibを使ってそれらを描画する方法を学びました。