파이톤으로 하트 그리기.

10843 단어 Python

개요


나는 책 한 권을 샀다수학 입문.얻기 어려운 기회에 저는'도표로 제2장 데이터를 시각화'를 참고하여 어떤 도표를 그려보려고 합니다.귀여운 그래픽이 좋아서 그려봤어요.
우선 사전 준비로 matplotlib의 설정문서를 작성한다.MacOS 환경에서 차트backend를 표시하고 차트 제목에 일본어를 사용하려면 font.family를 지정해야 합니다.
~/.matplotlib/matplotlibrc
backend : TkAgg
font.family : Ricty Diminished
주제의 드로잉으로 이동합니다.Heart Curve 페이지의 공식을 사용했습니다.
$x = 16sin^3(t)$
$y = 13cos(t)-5cos(2t)-2cos(3t)-cos(4t)$
draw_heart.py
from matplotlib import pyplot as plt
from math import pi, sin, cos


def draw_graph(x, y, title, color):
  plt.title(title)
  plt.plot(x, y, color=color)
  plt.show()


# range() 関数の浮動小数点数バージョン
# (参考) Pythonからはじめる数学入門 2.4.2.1 等間隔浮動小数点数の生成
def frange(start, final, increment=0.01):
  numbers = []

  while start < final:
    numbers.append(start)
    start = start + increment

  return numbers


def draw_heart():
  intervals = frange(0, 2 * pi)
  x = []
  y = []

  for t in intervals:
    x.append(16 * sin(t) ** 3)
    y.append(13 * cos(t) - 5 * cos(2 * t) - 2 * cos(3 * t) - cos(4 * t))

  draw_graph(x, y, title='ハート', color='#FF6597')


if __name__ == '__main__':
  try:
    draw_heart()
  except KeyboardInterrupt:
    # control + C で終了する。
    pass
Python 스크립트를 실행하면 그림% 1개의 캡션을 편집했습니다.귀엽다


위 스크립트에서 구현된 frrange 함수는 NumPyarange 함수로 대체되었습니다.넘피에는 pi,sin,cos 등의 함수도 갖춰져 있으며, 이 모듈을 사용할 때math도 모듈이 필요 없다.
draw_heart.py
from matplotlib import pyplot as plt
from numpy import arange, pi, sin, cos


def draw_graph(x, y, title, color):
  plt.title(title)
  plt.plot(x, y, color=color)
  plt.show()


def draw_heart():
  intervals = arange(0, 2 * pi, 0.01)
  x = []
  y = []

  for t in intervals:
    x.append(16 * sin(t) ** 3)
    y.append(13 * cos(t) - 5 * cos(2 * t) - 2 * cos(3 * t) - cos(4 * t))

  draw_graph(x, y, title='ハート', color='#FF6597')


if __name__ == '__main__':
  try:
    draw_heart()
  except KeyboardInterrupt:
    pass

좋은 웹페이지 즐겨찾기