Plotting Trig Functions and Help with Streamlining Code - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: Code Review (https://python-forum.io/forum-46.html) +--- Thread: Plotting Trig Functions and Help with Streamlining Code (/thread-31775.html) |
Plotting Trig Functions and Help with Streamlining Code - Dasiey12 - Jan-02-2021 Hi I am plotting a unit circle in Matlibplot. I am using a Jupiter Notebook to run the code. I am really looking for a way to shorten the code. I found the x and y coordinates for the angles 30, 45, 60, 90, and the rest of the angles that are always on the unit circle. I was wondering if there is a faster way to draw these lines? Is there away to find slope of each line and plot it? Here is my code. import numpy as np import matplotlib.pyplot as plt fig = plt.figure(figsize=(5,5)) ax = fig.add_subplot(1,1,1) ax.spines['left'].set_position(('axes',.5)) ax.yaxis.set_ticks_position('left') plt.ylim(-2,2) ax.spines['bottom'].set_position(("axes", .5)) plt.xlim(-2,2) x_theta_0 = [1, 0, -1] y_theta_0 = [0,0,0] x_theta_30 = [np.sqrt(3)/2, 0, -np.sqrt(3)/2] y_theta_30 = [1/2, 0 , -1/2] x_theta_45 = [np.sqrt(2)/2, 0, -np.sqrt(2)/2] y_theta_45 = [np.sqrt(2)/2, 0, -np.sqrt(2)/2] x_theta_60 = [1/2, 0, -1/2] y_theta_60 = [np.sqrt(3)/2, 0, -np.sqrt(3)/2] x_theta_90 = [0, 0, 0] y_theta_90 = [1, 0, -1] x_theta_120 = [-1/2, 0, 1/2] y_theta_120 = [np.sqrt(3)/2, 0, -np.sqrt(3)/2] x_theta_135 = [-np.sqrt(2)/2, 0, np.sqrt(2)/2] y_theta_135 = [np.sqrt(2)/2, 0, -np.sqrt(2)/2] x_theta_150 = [-np.sqrt(3)/2, 0, np.sqrt(3)/2] y_theta_150 = [1/2, 0, -1/2] x_tan_30 = [1, 1] y_tan_30 = [0, np.sqrt(3)/3] plt.plot(x_theta_0, y_theta_0) plt.plot(x_theta_30, y_theta_30) plt.plot(x_theta_45, y_theta_45) plt.plot(x_theta_60, y_theta_60) plt.plot(x_theta_90, y_theta_90) plt.plot(x_theta_120, y_theta_120) plt.plot(x_theta_135, y_theta_135) plt.plot(x_theta_150, y_theta_150) plt.plot(x_tan_30, y_tan_30) c = plt.Circle((0,0), 1) plt.gca().add_artist(c)The image below is my output. RE: Plotting Trig Functions and Help with Streamlining Code - Gribouillis - Jan-03-2021 Numpy knows trigonometric functions. No need to hard code their values import matplotlib.pyplot as plt import numpy as np theta = np.deg2rad(np.array([30, 45, 60, 90, 120, 135, 150])) x, y = np.cos(theta), np.sin(theta) x = np.stack((-x, x)).T y = np.stack((-y, y)).T print(x) print(y) fig, ax = plt.subplots() for u, v in zip(x, y): ax.plot(u, v) ax.set(aspect='equal') fig.savefig('foo.pdf') |