티스토리 뷰

 

https://www.youtube.com/watch?v=KHGoFDB-raE

출처는 다음 영상입니다. 해당 포스팅은 파이썬에대한 기초적인 선행지식은 있다고 가정합니다.

 

[3B1B 따라잡기 list]

2023.05.11 - [Computer/코딩 개꿀팁] - [3B1B 따라잡기 with Manim] 1. Manim 설치 with vscode

2023.05.12 - [Computer/코딩 개꿀팁] - [3B1B 따라잡기 with Manim] 2. How to create Scene

2023.05.15 - [Computer/코딩 개꿀팁] - [3B1B 따라잡기 with Manim] 3. Error message 파악하기

2023.05.15 - [Computer/코딩 개꿀팁] - [3B1B 따라잡기 with Manim] 4. Animation Updaters

2023.05.16 - [Computer/코딩 개꿀팁] - [3B1B 따라잡기 with Manim] 5. ValueTracker

 

이번 포스팅에서는 좌표계와 좌표계 위에 plot을 그리는 방법을 배워본다.

 

먼저 가장 간단한 좌표계를 그리는 방법을 알아보자. 

class Graphing(Scene):
    def construct(self):

        plane = NumberPlane(x_range=[-4,4,1], y_range=[0,9,1]).to_edge(DOWN).add_coordinates()

        self.play(DrawBorderThenFill(plane))
        self.wait(2)

NumberPlane() Mobject를 이용해 좌표계를 나타낼 수 있다. x_range는 나타낼 좌표의 x좌표 범위를 설정하고 y_range는 y좌표의 범위를 설정한다. [min, max, interval], .to_edge(DOWN)을 이용해 화면의 아래쪽으로 좌표계를 끌어맞춘다. add_coordinates() 함수를 이용하면 좌표위에 숫자를 표현할 수 있다.

그런데 문제가 있다. y좌표를 0에서 9까지 설정했는데 공간이 부족해서 그림은 7까지밖에 표현이 안된다. 어떻게 해야할까? 이것은 x_lengthy_length 옵션으로 조정이 가능하다. 다음과 같이 두 옵션의 코드를 수정하고 결과를 확인해보자.

class Graphing(Scene):
    def construct(self):
		# 기존 코드 # 
        # plane = NumberPlane(x_range=[-4,4,1], y_range=[0,9,1]).to_edge(DOWN).add_coordinates()

		# 수정된 코드 #
        plane = NumberPlane(x_range=[-4,4,1], y_range=[0,9,1],
                    x_length=7, y_length=7).to_edge(DOWN).add_coordinates()
                    
        self.play(DrawBorderThenFill(plane))
        self.wait(2)

 

공간에 모든 좌표가 그려지는 것을 확인할 수 있다.

x_length와 y_length는 사용자가 편의에 맞춰 알아서 조절해보다보면 금방 감을 익힐 수 있을 것이다. 이번에는 좌표계 위에 plot을 그려보자. 가장 간단한 2차 함수 그래프를 그려볼 것이다. 코드를 다음과 같이 짜고 실행 결과를 확인해보자

class Graphing(Scene):
    def construct(self):

        plane = NumberPlane(x_range=[-4,4,1], y_range=[0,9,1],
                            x_length=7, y_length=7).to_edge(DOWN).add_coordinates()

        parab = plane.plot(lambda x : x**2, x_range=(-3,3), color=GREEN)

        self.play(DrawBorderThenFill(plane))
        self.play(FadeIn(parab))
        self.wait(2)

parab 변수에 plot을 저장하는데 plane에 저장된 NumberPlane Mobject에 .plot()을 이용해서 그래프를 그린다. 이때 lambda 함수를 이용해 그려질 함수를 만들어주고 plot이 그려질 범위를 x_range로 설정해준다. color은 색깔지정. 이후에 self.play()를 통해 parab변수도 호출해주면 plane위에 parab graph가 그려진다.

이제 약간의 디테일을 추가해보자. 

  1. 좌표계 위에 x축과 y축을 나타내기
  2. 함수에 label달아주기
class Graphing(Scene):
    def construct(self):

        plane = NumberPlane(x_range=[-4,4,1], y_range=[0,9,1],
                            x_length=7, y_length=7).to_edge(DOWN).add_coordinates()

        parab = plane.plot(lambda x : x**2, x_range=(-3,3), color=GREEN)
        x_label = plane.get_x_axis_label("x")
        y_label = plane.get_y_axis_label("y=f(x)")
        func_label = MathTex("f(x)=x^{2}").scale(0.6).next_to(parab, RIGHT, buff=0).set_color(GREEN)

        self.play(DrawBorderThenFill(plane))
        self.play(FadeIn(VGroup(x_label, parab, func_label)), run_time=1.5)
        self.wait(3)

plane 변수에 .get_x_axis_label()과 .get_y_axis_label() 함수를 이용하면 (get보단 set이 낫지 않았나. 왜 get인지는 약간 이해가 안가는 부분) 좌표계에 원하는 텍스트를 써서 축을 나타낼 수 있다. func_label은 함수에 붙이는 label을 저장하는 변수이고 MathTex()함수를 이용해 함수 명을 적어주면 된다. 이때 따옴표 내부에 들어가는 수식은 LaTeX를 기반으로 하는데 이 사이트를 참고해서 작성하면 아마 왠만큼 필요한 수준에서의 수식 작성은 모두 가능할 것이다. 그 외 자잘한 옵션들은 앞선 포스팅들에서 거의 대부분 설명하였기 때문에 넘어간다.

https://atomurl.net/math/

 

TeX equation editor (Mathematical Formulas)

Online equation editor for writing math equations, expressions, mathematical characters, and operations. You can also generate an image of a mathematical formula using the TeX language. This is useful for displaying complex formulas on your web page.

atomurl.net

 

마지막으로 고등학교 시절 기억을 더듬거려 그래프 아래 면적을 적분하던 우리의 모습을 기억해보자. 그리고 그래프의 아래 면적을 적분하는 아래 코드를 짜보자

class Graphing(Scene):
    def construct(self):

        plane = NumberPlane(x_range=[-4,4,1], y_range=[0,9,1],
                            x_length=7, y_length=7).to_edge(DOWN).add_coordinates()

        parab = plane.plot(lambda x : x**2, x_range=(-3,3), color=GREEN)
        x_label = plane.get_x_axis_label("x")
        y_label = plane.get_y_axis_label("y=f(x)")
        func_label = MathTex("f(x)=x^{2}").scale(0.6).next_to(parab, RIGHT, buff=0).set_color(GREEN)
		
        # 추가된 부분 #
        area = plane.get_riemann_rectangles(graph=parab, x_range=[-2, 3], dx=0.1,
                                            stroke_width=0.5, stroke_color=WHITE)

        self.play(DrawBorderThenFill(plane))
        self.play(FadeIn(VGroup(x_label, parab, func_label)), run_time=1.5)
        self.wait(1)

		# 추가된 부분 #
        self.play(Create(area), run_time=1)
        self.wait(3)

실행결과는 다음과 같다.

area 변수에 적분 그래프를 저장하기 위해 plane.get_riemann_rectangles()함수를 이용한다. graph 옵션을 통해 어떤 그래프에 대해 적분을 하는지를 지정해주고, 적분 범위를 x_range를 통해 설정해준다. 여기서는 -2~3까지 적분되는것을 볼 수 있다. dx는 알다시피 각 막대의 너비이고 stroke옵션은 직관적으로 바로 이해할 수 있을것이다.

이번 포스팅은 여기까지 

댓글