Last active
October 23, 2021 07:08
-
-
Save ryanorsinger/b62042c8b12ca74dd3bdc27fa7291401 to your computer and use it in GitHub Desktop.
Plot tan(x) with matplotlib and numpy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import matplotlib.pyplot as plt | |
import numpy as np | |
import math | |
# .linspace arguments are (start, end, number_of_steps) | |
x = np.linspace(-2 * math.pi, 2 * math.pi, 1000) | |
y = np.tan(x) | |
# This operation inserts a NaN where the difference between successive points is negative | |
# NaN means "Not a Number" and NaNs are not plotted or connected | |
# I found this by doing a search for "How to plot tan(x) in matplotlib without the connecting lines between asymtotes" | |
y[:-1][np.diff(y) < 0] = np.nan | |
# show grid | |
plt.grid() | |
plt.xlabel("x") | |
plt.ylabel("$tan(x)$") | |
# Set the x and y axis cutoffs | |
plt.ylim(-10,10) | |
plt.xlim(-2 * math.pi, 2 * math.pi) | |
# x_labels in radians | |
# For a more programmatic approach to radians, see https://matplotlib.org/3.1.1/gallery/units/radian_demo.html | |
radian_multiples = [-2, -3/2, -1, -1/2, 0, 1/2, 1, 3/2, 2] | |
radians = [n * math.pi for n in radian_multiples] | |
radian_labels = ['$-2\pi$', '$-3\pi/2$', '$\pi$', '$-\pi/2$', '0', '$\pi/2$', '$\pi$', '$3\pi/2$', '$2\pi$'] | |
plt.xticks(radians, radian_labels) | |
plt.title("$y = tan(x)$", fontsize=14) | |
plt.plot(x, y) | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment