Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to plot y=1/x as a single graph in Python?
To plot the function y=1/x as a single graph in Python, we use matplotlib and numpy libraries. The hyperbola y=1/x has two branches separated by asymptotes at x=0 and y=0.
Steps to Plot y=1/x
- Set the figure size and adjust the padding between and around the subplots
- Create data points using numpy, excluding x=0 to avoid division by zero
- Plot x and 1/x data points using plot() method
- Add labels and legend for better visualization
- Display the figure using show() method
Example
Here's how to plot the hyperbola y=1/x with proper handling of the discontinuity at x=0 ?
import numpy as np
import matplotlib.pyplot as plt
# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create data points, avoiding x=0
x = np.linspace(-10, 10, 1001)
x = x[x != 0] # Remove x=0 to avoid division by zero
# Plot the function y = 1/x
plt.plot(x, 1/x, label='$f(x)=\frac{1}{x}$', color='blue')
# Add grid and labels
plt.grid(True, alpha=0.3)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Graph of y = 1/x')
plt.legend(loc='upper left')
# Set axis limits for better visualization
plt.xlim(-10, 10)
plt.ylim(-10, 10)
plt.show()
Handling the Discontinuity
Since y=1/x is undefined at x=0, we need to create separate arrays for positive and negative x values to properly display the two branches ?
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [8.00, 6.00]
plt.rcParams["figure.autolayout"] = True
# Create separate arrays for positive and negative x values
x_positive = np.linspace(0.1, 10, 500)
x_negative = np.linspace(-10, -0.1, 500)
# Plot both branches
plt.plot(x_positive, 1/x_positive, 'b-', label='$f(x)=\frac{1}{x}$')
plt.plot(x_negative, 1/x_negative, 'b-')
# Add asymptotes (optional visual aid)
plt.axhline(y=0, color='gray', linestyle='--', alpha=0.5, label='y=0 (asymptote)')
plt.axvline(x=0, color='gray', linestyle='--', alpha=0.5, label='x=0 (asymptote)')
# Formatting
plt.grid(True, alpha=0.3)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Graph of y = 1/x with Asymptotes')
plt.legend()
plt.xlim(-10, 10)
plt.ylim(-10, 10)
plt.show()
Key Properties of y=1/x
- Domain: All real numbers except x=0
- Range: All real numbers except y=0
- Asymptotes: Vertical asymptote at x=0, horizontal asymptote at y=0
- Symmetry: Odd function, symmetric about the origin
Conclusion
Plotting y=1/x requires careful handling of the discontinuity at x=0. Use separate arrays for positive and negative x values or filter out x=0 to create a clean hyperbola visualization. Adding asymptotes and grid lines helps illustrate the function's behavior.
Advertisements
