アルゴリズム

[Python] コッホ曲線をmatplotlibで描く方法

コッホ曲線は、フラクタル図形の一種で、再帰的に直線を分割して生成されます。

Pythonでコッホ曲線を描くには、再帰関数を用いて各ステップで直線を3等分し、中央の部分を正三角形の一辺に置き換える操作を繰り返します。

matplotlibを使って描画するには、再帰的に生成された座標をプロットします。

matplotlib.pyplot.plot()関数を使用して、生成された点を線で結び、コッホ曲線を描画します。

コッホ曲線とは

コッホ曲線は、フラクタル幾何学の一例であり、自己相似性を持つ美しい図形です。

最初は正三角形から始まり、各辺の中点を結ぶことで新たな三角形を作り出し、これを繰り返すことで複雑な形状が生成されます。

このプロセスを無限に続けることで、無限の詳細を持つ曲線が形成されます。

コッホ曲線は、自然界の多くの現象やアートに応用されており、数学的な美しさと視覚的な魅力を兼ね備えています。

Pythonでコッホ曲線を描くための準備

必要なライブラリのインストール

コッホ曲線を描くためには、matplotlibというライブラリが必要です。

以下のコマンドを使用して、matplotlibをインストールします。

pip install matplotlib

matplotlibの基本的な使い方

matplotlibは、Pythonでデータを可視化するための強力なライブラリです。

基本的な使い方は以下の通りです。

  1. ライブラリをインポートする
  2. データを準備する
  3. プロットを作成する
  4. 表示する

以下は、簡単な折れ線グラフを描くサンプルコードです。

import matplotlib.pyplot as plt
# データの準備
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
# プロットの作成
plt.plot(x, y)
# 表示
plt.show()

このコードを実行すると、指定したデータに基づいた折れ線グラフが表示されます。

再帰関数の基礎知識

コッホ曲線を描くためには、再帰関数を使用します。

再帰関数とは、関数が自分自身を呼び出すことで問題を解決する手法です。

再帰を使用することで、複雑な形状を簡潔に表現できます。

再帰関数には、基本ケースと再帰ケースが必要です。

基本ケースは再帰を終了させる条件であり、再帰ケースは関数が自分自身を呼び出す部分です。

コッホ曲線を描くためのアルゴリズム

コッホ曲線を描くためのアルゴリズムは以下の手順で構成されます。

  1. 初期の正三角形を描く。
  2. 各辺を3等分し、中点を結ぶことで新たな三角形を作成する。
  3. 新たに作成した三角形の頂点を外側に押し出す。
  4. このプロセスを再帰的に繰り返す。

このアルゴリズムを実装することで、コッホ曲線を描くことができます。

コッホ曲線の実装

コッホ曲線の再帰関数の作成

コッホ曲線を描くためには、再帰関数を作成します。

この関数は、指定された深さまで再帰的に呼び出され、各辺を分割して新しい三角形を生成します。

以下は、コッホ曲線の再帰関数の基本的な構造です。

def koch_curve(ax, start, end, depth):
    if depth == 0:
        ax.plot([start[0], end[0]], [start[1], end[1]], color='blue')
    else:
        # 各辺を3等分する
        third = (end[0] - start[0]) / 3, (end[1] - start[1]) / 3
        point1 = (start[0] + third[0], start[1] + third[1])
        point2 = (start[0] + 2 * third[0], start[1] + 2 * third[1])
        
        # 新しい頂点を計算
        peak = (
            (point1[0] + point2[0]) / 2 - (point2[1] - point1[1]) * (3 ** 0.5) / 6,
            (point1[1] + point2[1]) / 2 + (point2[0] - point1[0]) * (3 ** 0.5) / 6
        )
        
        # 再帰的に描画
        koch_curve(ax, start, point1, depth - 1)
        koch_curve(ax, point1, peak, depth - 1)
        koch_curve(ax, peak, point2, depth - 1)
        koch_curve(ax, point2, end, depth - 1)

座標の計算方法

コッホ曲線では、各辺を3等分し、新たな三角形の頂点を計算します。

具体的には、以下の手順で座標を計算します。

  1. 始点と終点の座標を取得する。
  2. 各辺を3等分し、1/3と2/3の位置に新しい点を計算する。
  3. 新しい三角形の頂点を、2つの点の中点から外側に押し出すことで求める。

この計算により、再帰的に新しい形状が生成されます。

matplotlibでの描画方法

matplotlibを使用してコッホ曲線を描画するには、以下の手順を実行します。

  1. matplotlibをインポートし、描画用のFigureとAxesを作成する。
  2. 初期の正三角形の3つの頂点を指定する。
  3. 再帰関数を呼び出してコッホ曲線を描画する。
  4. 描画結果を表示する。

以下は、matplotlibを使用した描画のサンプルコードです。

import matplotlib.pyplot as plt
# コッホ曲線の描画
def draw_koch_curve(depth):
    fig, ax = plt.subplots()
    ax.set_aspect('equal')
    
    # 正三角形の頂点
    points = [(0, 0), (1, 0), (0.5, (3 ** 0.5) / 2)]
    
    # 再帰関数を呼び出す
    koch_curve(ax, points[0], points[1], depth)
    koch_curve(ax, points[1], points[2], depth)
    koch_curve(ax, points[2], points[0], depth)
    
    plt.axis('off')  # 軸を非表示にする
    plt.show()
# 深さを指定して描画
draw_koch_curve(4)

実行結果の確認

上記のコードを実行すると、指定した深さ(この例では4)に基づいてコッホ曲線が描画されます。

描画された図形は、自己相似性を持つ美しいフラクタル形状となります。

深さを増やすことで、より複雑な形状が生成されることを確認できます。

完全なサンプルコード

以下は、コッホ曲線を描画するための完全なサンプルコードです。

import matplotlib.pyplot as plt
def koch_curve(ax, start, end, depth):
    if depth == 0:
        ax.plot([start[0], end[0]], [start[1], end[1]], color='blue')
    else:
        third = (end[0] - start[0]) / 3, (end[1] - start[1]) / 3
        point1 = (start[0] + third[0], start[1] + third[1])
        point2 = (start[0] + 2 * third[0], start[1] + 2 * third[1])
        
        peak = (
            (point1[0] + point2[0]) / 2 - (point2[1] - point1[1]) * (3 ** 0.5) / 6,
            (point1[1] + point2[1]) / 2 + (point2[0] - point1[0]) * (3 ** 0.5) / 6
        )
        
        koch_curve(ax, start, point1, depth - 1)
        koch_curve(ax, point1, peak, depth - 1)
        koch_curve(ax, peak, point2, depth - 1)
        koch_curve(ax, point2, end, depth - 1)
def draw_koch_curve(depth):
    fig, ax = plt.subplots()
    ax.set_aspect('equal')
    
    points = [(0, 0), (1, 0), (0.5, (3 ** 0.5) / 2)]
    
    koch_curve(ax, points[0], points[1], depth)
    koch_curve(ax, points[1], points[2], depth)
    koch_curve(ax, points[2], points[0], depth)
    
    plt.axis('off')
    plt.show()
draw_koch_curve(4)

このコードを実行することで、コッホ曲線が描画されます。

深さを変更することで、異なる複雑さの曲線を楽しむことができます。

コッホ曲線の描画をカスタマイズする

色や線の太さを変更する方法

matplotlibでは、描画する線の色や太さを簡単に変更できます。

plot関数の引数にcolorlinewidthを指定することで、これらのプロパティを設定できます。

以下は、色を赤に、線の太さを2に変更した例です。

def koch_curve(ax, start, end, depth):
    if depth == 0:
        ax.plot([start[0], end[0]], [start[1], end[1]], color='red', linewidth=2)
    else:
        # 省略: 再帰処理

このように、color='red'linewidth=2を追加することで、コッホ曲線の見た目をカスタマイズできます。

再帰の深さを調整する方法

コッホ曲線の再帰の深さを調整することで、描画される曲線の複雑さを変えることができます。

draw_koch_curve関数を呼び出す際に、引数として深さを指定します。

例えば、深さを3に設定する場合は以下のようにします。

draw_koch_curve(3)

深さを増やすと、より詳細な曲線が描画されますが、描画にかかる時間も増加します。

適切な深さを選ぶことが重要です。

描画範囲を変更する方法

描画範囲を変更するには、matplotlibset_xlimset_ylimメソッドを使用します。

これにより、表示する座標の範囲を指定できます。

以下は、描画範囲を変更する例です。

def draw_koch_curve(depth):
    fig, ax = plt.subplots()
    ax.set_aspect('equal')
    
    # 描画範囲を設定
    ax.set_xlim(-0.5, 1.5)
    ax.set_ylim(-0.5, 1.5)
    
    points = [(0, 0), (1, 0), (0.5, (3 ** 0.5) / 2)]
    
    koch_curve(ax, points[0], points[1], depth)
    koch_curve(ax, points[1], points[2], depth)
    koch_curve(ax, points[2], points[0], depth)
    
    plt.axis('off')
    plt.show()

このように、set_xlimset_ylimを使うことで、描画範囲を自由に調整できます。

アニメーションでコッホ曲線を描く

コッホ曲線をアニメーションで描くには、matplotlib.animationモジュールを使用します。

以下は、再帰の深さを徐々に増やしながらコッホ曲線を描くアニメーションの例です。

import matplotlib.pyplot as plt
import matplotlib.animation as animation
def update(frame):
    ax.clear()
    ax.set_aspect('equal')
    ax.set_xlim(-0.5, 1.5)
    ax.set_ylim(-0.5, 1.5)
    
    points = [(0, 0), (1, 0), (0.5, (3 ** 0.5) / 2)]
    for i in range(3):
        koch_curve(ax, points[i], points[(i + 1) % 3], frame)
fig, ax = plt.subplots()
ani = animation.FuncAnimation(fig, update, frames=range(1, 6), repeat=False)
plt.show()

このコードを実行すると、再帰の深さが1から5まで増加しながらコッホ曲線が描かれるアニメーションが表示されます。

アニメーションを通じて、コッホ曲線の生成過程を視覚的に楽しむことができます。

応用例

コッホ雪片の描画

コッホ雪片は、コッホ曲線を3つの辺に適用したフラクタル図形です。

最初に正三角形を描き、その各辺にコッホ曲線を適用することで、雪片のような形状が生成されます。

以下は、コッホ雪片を描くためのサンプルコードです。

def draw_koch_snowflake(depth):
    fig, ax = plt.subplots()
    ax.set_aspect('equal')
    
    # 正三角形の頂点
    points = [(0, 0), (1, 0), (0.5, (3 ** 0.5) / 2)]
    
    # 各辺にコッホ曲線を描画
    for i in range(3):
        koch_curve(ax, points[i], points[(i + 1) % 3], depth)
    
    plt.axis('off')
    plt.show()
draw_koch_snowflake(4)

このコードを実行すると、コッホ雪片が描画されます。

深さを変更することで、雪片の複雑さを調整できます。

他のフラクタル図形の描画

コッホ曲線を基にした他のフラクタル図形も描くことができます。

例えば、シェルピンスキーの三角形や、ドラゴン曲線などがその例です。

これらの図形も再帰的なアルゴリズムを使用して描画できます。

以下は、シェルピンスキーの三角形を描くためのサンプルコードです。

def sierpinski_triangle(ax, points, depth):
    if depth == 0:
        ax.fill(*zip(*points), color='green')
    else:
        mid1 = ((points[0][0] + points[1][0]) / 2, (points[0][1] + points[1][1]) / 2)
        mid2 = ((points[1][0] + points[2][0]) / 2, (points[1][1] + points[2][1]) / 2)
        mid3 = ((points[0][0] + points[2][0]) / 2, (points[0][1] + points[2][1]) / 2)
        
        sierpinski_triangle(ax, [points[0], mid1, mid3], depth - 1)
        sierpinski_triangle(ax, [points[1], mid1, mid2], depth - 1)
        sierpinski_triangle(ax, [points[2], mid2, mid3], depth - 1)
def draw_sierpinski_triangle(depth):
    fig, ax = plt.subplots()
    ax.set_aspect('equal')
    
    points = [(0, 0), (1, 0), (0.5, (3 ** 0.5) / 2)]
    sierpinski_triangle(ax, points, depth)
    
    plt.axis('off')
    plt.show()
draw_sierpinski_triangle(4)

3Dでのコッホ曲線の描画

3Dでコッホ曲線を描くには、matplotlibの3Dプロット機能を使用します。

以下は、3Dでコッホ曲線を描くためのサンプルコードです。

from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt

def koch_curve_3d(ax, start, end, depth):
    if depth == 0:
        ax.plot([start[0], end[0]], [start[1], end[1]], [start[2], end[2]], color='blue')
    else:
        third = (end[0] - start[0]) / 3, (end[1] - start[1]) / 3, (end[2] - start[2]) / 3
        point1 = (start[0] + third[0], start[1] + third[1], start[2] + third[2])
        point2 = (start[0] + 2 * third[0], start[1] + 2 * third[1], start[2] + 2 * third[2])
        
        peak = (
            (point1[0] + point2[0]) / 2,
            (point1[1] + point2[1]) / 2 + (3 ** 0.5) / 6,
            (point1[2] + point2[2]) / 2
        )
        
        koch_curve_3d(ax, start, point1, depth - 1)
        koch_curve_3d(ax, point1, peak, depth - 1)
        koch_curve_3d(ax, peak, point2, depth - 1)
        koch_curve_3d(ax, point2, end, depth - 1)

def draw_koch_curve_3d(depth):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    
    points = [(0, 0, 0), (1, 0, 0), (0.5, (3 ** 0.5) / 2, 0)]
    
    for i in range(3):
        koch_curve_3d(ax, points[i], points[(i + 1) % 3], depth)
    
    ax.set_box_aspect([1, 1, 1])  # 修正箇所
    plt.show()

draw_koch_curve_3d(3)

コッホ曲線を使ったアート作品の作成

コッホ曲線は、アート作品のインスピレーションとしても利用できます。

フラクタルの特性を活かして、色や形を組み合わせることで、独自のアート作品を作成できます。

以下は、コッホ曲線を使ったアート作品のサンプルコードです。

def draw_fractal_art(depth):
    fig, ax = plt.subplots()
    ax.set_aspect('equal')
    
    points = [(0, 0), (1, 0), (0.5, (3 ** 0.5) / 2)]
    
    for i in range(3):
        koch_curve(ax, points[i], points[(i + 1) % 3], depth)
    
    # 色をランダムに変更
    for i in range(10):
        ax.plot([np.random.rand(), np.random.rand()], [np.random.rand(), np.random.rand()], color=np.random.rand(3,))
    
    plt.axis('off')
    plt.show()
draw_fractal_art(3)

このように、コッホ曲線を利用して様々なアート作品を作成することができます。

色や形を自由に組み合わせることで、独自の作品を楽しむことができます。

まとめ

この記事では、コッホ曲線の基本的な概念から始まり、Pythonを用いてその描画方法を詳しく解説しました。

また、コッホ曲線の実装やカスタマイズ方法、さらには応用例としてコッホ雪片や他のフラクタル図形の描画方法についても触れました。

これを機に、フラクタルの魅力を体験し、自分自身のプロジェクトに応用してみることをお勧めします。

関連記事

Back to top button
目次へ