ハニカム構造をmatplotlibで書いてみた
占いCO! StudentSです。
真占いっぽく見えない挙動が多く見受けられますが、
これは、
- 呪殺対応のために色々準備をしたり
- 狐候補に〇を出さないように細心の注意を払ったり
- 2000戦越えの仲間の狼からアドバイスをいただいる
からではありません!!
素です。
挙動不審だからといって、処刑などしないようにお願いします。
生存権を行使します!
さて、PyCheckIOに下記のような問題があり、matplotlibの練習も兼ねて、6角形の描画をやってみることにしました。
import numpy as np import matplotlib.pyplot as plt from matplotlib import patches def _range(p): assert p.ndim == 2 and p.shape[1] == 2 xmin, ymin = np.min(p[:, 0]), np.min(p[:, 1]) xmax, ymax = np.max(p[:, 0]), np.max(p[:, 1]) return xmin, ymin, xmax, ymax def make_hexagon(center, length): theta = np.arange(0, 6) * 2 * np.pi / 6 x = np.cos(theta) * length y = np.sin(theta) * length xy = np.stack([x, y], axis=-1) xy = xy + np.array(center) return xy def make_centers(length, n_row=9, n_column=27): """ Return: dict. (row_index, column_index) -> ``center``. """ result = dict() x, y = 0, 0 for c in range(n_column): x = 3 / 2 * length * c y = 0 if c % 2 == 0 else np.sqrt(3) / 2 * length for r in range(n_row): y += np.sqrt(3) * length result[r, c] = (x, y) return result if __name__ == "__main__": fig, ax = plt.subplots() centers = make_centers(1) r = [0, 0, 0, 0] for key, center in centers.items(): p = make_hexagon(center, 1) xmin, ymin, xmax, ymax = _range(p) r[0] = min(xmin, r[0]) r[1] = min(ymin, r[1]) r[2] = max(xmax, r[2]) r[3] = max(ymax, r[3]) color = "C1" if (key[0] + key[1]) % 2 == 0 else "C2" patch = patches.Polygon(p, edgecolor="black", facecolor=color) ax.add_patch(patch) ax.set_xlim((r[0], r[2])) ax.set_ylim((r[1], r[3])) ax.add_patch(patch) ax.invert_yaxis() ax.tick_params(labelbottom=False, labeltop=False, labelleft=False) ax.set_aspect("equal") ax.set_title("Example of Hexagons.") fig.savefig("output.png", transparent=True)
あまりエレガントなコードではないですが、とりあえず、ちょっと綺麗な図ができてよかったよかった。 PyCheckIOの問題はまだ解けていないので、これから頑張りますー
Happy Halloween! の季節ですね... 「お菓子をくれなきゃ、いたずらしますよ?」そんなおだやかな会話で、小さな幸せを積み重ねていける1月になりますように。