![見出し画像](https://assets.st-note.com/production/uploads/images/108222582/rectangle_large_type_2_a0616c77dcc30e43a4b03ce00a688b92.png?width=1200)
フォトギャラリー用グラフ#6
この企画の目的:
毎日投稿のバッジ獲得のために、できるだけ楽をして記事を書く
「みんなのフォトギャラリー」で使える数学の画像を作る
図を見てるだけなら数学は思って貰えることを目指す
この回ではフラクタル図形を書きます。no+eでは、108Hassiumさんが本格的なフラクタル図形のグラフィックを描かれています。綺麗な描画のためにはProcessingというツールを用いるのが良いらしいです。勉強になります。
しかし、私の記事では手軽さを優先して、PythonとGoogle Colaboratory でフラクタル曲線を描きました。
描き方は、以下のWikipediaの記事の「例4:コッホ曲線」に従っています。
以下は、生成したコッホ曲線です。
![](https://assets.st-note.com/img/1686733047562-8IPWjd0U04.png?width=1200)
![](https://assets.st-note.com/img/1686733064081-SFKI2nxN96.png?width=1200)
![](https://assets.st-note.com/img/1686733078433-MymQHYm7mx.png?width=1200)
![](https://assets.st-note.com/img/1686733091172-XTrsPAgDJC.png?width=1200)
![](https://assets.st-note.com/img/1686733106447-2YpnVaVOpL.png?width=1200)
Pythonのコード
以下は、グラフの描画に用いたPythonのコードです。Google Collaboratory で実行しました。
import matplotlib.pyplot as plt
import numpy as np
# 文字列を生成するための関数
def P(c):
if c == 'F':
retv = 'F+F-F-F+F'
else:
retv = c
return retv
# 亀の向きを変える
def rotate_counterclockwise(l):
direction = l[0]
if direction == 'r':
l[0] = 'u'
elif direction == 'l':
l[0] = 'd'
elif direction == 'u':
l[0] = 'l'
elif direction == 'd':
l[0] = 'r'
else:
print("error")
return
def rotate_clockwise(l):
direction = l[0]
if direction == 'r':
l[0] = 'd'
elif direction == 'l':
l[0] = 'u'
elif direction == 'u':
l[0] = 'r'
elif direction == 'd':
l[0] = 'l'
else:
print("error")
return
# 亀を前進させる
def move_forward(l):
direction = l[0]
if direction == 'r':
l.insert(1,[l[1][0]+1, l[1][1]])
elif direction == 'l':
l.insert(1,[l[1][0]-1, l[1][1]])
elif direction == 'u':
l.insert(1,[l[1][0], l[1][1]+1])
elif direction == 'd':
l.insert(1,[l[1][0], l[1][1]-1])
else:
print("error")
# 生成された文字列にしたがって亀を移動させる
def move(l,c):
if c == '+':
rotate_counterclockwise(l)
elif c == '-':
rotate_clockwise(l)
elif c == 'F':
move_forward(l)
else:
print('error')
# メイン部分
w = 'F'
for n in range(6):
# 文字列の生成
s = w
for i in range(n):
#print(s)
tmp = ''
for c in s:
tmp = tmp + P(c)
s = tmp
# パスを生成
l = [ 'r', [0,0]]
for c in s:
move(l,c)
# パスを配列に変換
length = len(l)-1
x = np.zeros(length)
y = np.zeros(length)
for i in range(length):
x[i] = l[length-i][0]
y[i] = l[length-i][1]
plt.rcParams['font.size'] = 10 # デフォルトの文字サイズ
r = 5.0
fig, ax = plt.subplots(figsize=(1.91*r,r))
ax.axis("off")
ax.plot(x, y)
plt.savefig("graph-20230614-"+str(n)+".png",format="png",dpi=300)
plt.show()