X,Y rotation in python

Below is example of rotating the locations matrix by 45 degree anti clockwise. The locations are simply a list of X, Y. The rotation origin is 0, 0. If not at zero, simply subtract the origin point from the locations, and add them back after rotation.

The key here is a rotation matrix. Google why. There is a post on this wiki as well. The locations is transposed to align with the rotation matrix, and transposed back.



import math

import numpy as np


locations = np.array([[10, 5], [20, 17]])

rotated_anticlock = 45 #degree

radian = (rotated_anticlock / 180) * np.pi

rotation_matrix = [[math.cos(radian), -math.sin(radian)],[math.sin(radian), math.cos(radian)]]


rotated_xy = np.dot(rotation_matrix, locations.T)

rotated_locations = rotated_xy.T

rotated_locations


TO view the locations and the rotated locations for testing.


import matplotlib.pyplot as plt


fig, ax = plt.subplots(1,1,figsize=(4, 4))

ax.scatter(locations[:, 0], locations[:, 1], color='b')

ax.scatter(rotated_locations[:, 0], rotated_locations[:, 1], color='r')

plt.xlim((0, 30))

plt.ylim((0, 30))

plt.show()