[python] 파이썬 2차원 벡터 회전 구현 (2차원 좌표계 그래프 그리기)

파이썬을 활용하여 2차원 벡터를 회전하는 함수를 구현해 보겠습니다. 



아래 공식은 2차원 벡터 (x, y)를 원점기준 회전각 θ로 회전시켰을 때 결과 벡터 (x', y')를 반환합니다.



아래는 위 공식을 구현한 파이썬 코드입니다.


import numpy as np
import matplotlib.pyplot as plt

def rotate_vector(vector, angle):
    """
    2차원 벡터를 주어진 각도만큼 회전.
    vector = (x,y)
    angle = 반시계반향 각도(라디안)
    회전된 2차원 벡터를 Numpy array로 반환
    """
    
    rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)],
                                [np.sin(angle), np.cos(angle)]])
    
    return np.dot(rotation_matrix, vector)


vec = [1, 1]
theta = np.pi/2
r = rotate_vector(vec, theta)
print(r)


위 함수를 이용하여 그래프를 그려보면 아래와 같습니다.


그래프를 보면 빨간색 초기점에서 원점 기준으로 90도 회전하여 파란점이 생성된 것을 확인할 수 있습니다.


위 그래프를 출력하는 코드는 아래와 같습니다.


# Define the x and y ranges, and the tick interval for both axes.
xmin, xmax, ymin, ymax = -5, 5, -5, 5
ticks_frequency = 1

#Create a figure and an axes object.
fig, ax = plt.subplots(figsize=(10, 10))

#Apply the ranges to the axes.
ax.set(xlim=(xmin-1, xmax+1), ylim=(ymin-1, ymax+1), aspect='equal')


# Set both axes to the zero position.
ax.spines['bottom'].set_position('zero')
ax.spines['left'].set_position('zero')

# Hide the top and right spines.
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

# Set the x and y labels, and add an origin label.
ax.set_xlabel('$x$', size=14, labelpad=-24, x=1.02)
ax.set_ylabel('$y$', size=14, labelpad=-21, y=1.02, rotation=0)
 
plt.text(0.49, 0.49, r"$O$", ha='right', va='top',
    transform=ax.transAxes,
    horizontalalignment='center', fontsize=14)

# Now create the x and the y ticks, and apply them to both axes.
x_ticks = np.arange(xmin, xmax+1, ticks_frequency)
y_ticks = np.arange(ymin, ymax+1, ticks_frequency)
ax.set_xticks(x_ticks[x_ticks != 0])
ax.set_yticks(y_ticks[y_ticks != 0])
ax.set_xticks(np.arange(xmin, xmax+1), minor=True)
ax.set_yticks(np.arange(ymin, ymax+1), minor=True)

# Finally, add a grid.
ax.grid(which='both', color='grey', linewidth=1, linestyle='-', alpha=0.2)

plt.plot(vec[0], vec[1], 'ro', r[0], r[1], 'bo')


끝.

댓글

이 블로그의 인기 게시물

[PLC] PLC 아날로그 입출력 기본

NPN, PNP 트랜지스터 차이점

전력(kW) 계산하기 (직류, 교류 단상, 교류 삼상)

3선 결선식 센서의 타입 PNP, NPN

[아두이노] 가변저항(Potential Divider)과 전압분배(Voltage Divider)

제너 다이오드에 저항을 연결하는 이유

커패시터에 저장된 에너지 계산

3상 모터 전력에서 전류 계산하기 (How to Convert Three-Phase Power to Amps)

[공압밸브] 5포트 2웨이 & 4포트 2웨이, 단동 VS 복동 차이점

[PLC] PLC 입출력 타입 - 싱크 & 소스 (Sink & Source)