How to plot a function defined with def in Python? (Matplotlib)

To plot a function defined with def in Python, you need to create the function, generate data points, and use Matplotlib's plotting methods. This approach allows you to visualize mathematical functions easily.

Basic Steps

The process involves the following steps ?

  • Import necessary libraries (NumPy and Matplotlib)
  • Create a user-defined function using def
  • Generate x data points using NumPy's linspace()
  • Plot the function using plot() method
  • Display the plot using show() method

Example

Here's how to plot a custom mathematical function ?

import numpy as np
import matplotlib.pyplot as plt

# Set figure size and layout
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Define a custom function
def f(x):
    return np.sin(x) + x + x * np.sin(x)

# Generate x values
x = np.linspace(-10, 10, 100)

# Plot the function
plt.plot(x, f(x), color='red', linewidth=2)
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('Custom Function Plot')
plt.grid(True, alpha=0.3)

plt.show()

Multiple Functions Example

You can also plot multiple functions on the same graph ?

import numpy as np
import matplotlib.pyplot as plt

# Define multiple functions
def linear_func(x):
    return 2 * x + 1

def quadratic_func(x):
    return x**2 - 3*x + 2

def exponential_func(x):
    return np.exp(0.1 * x)

# Generate x values
x = np.linspace(-5, 5, 100)

# Plot all functions
plt.figure(figsize=(10, 6))
plt.plot(x, linear_func(x), label='Linear: 2x + 1', linewidth=2)
plt.plot(x, quadratic_func(x), label='Quadratic: x² - 3x + 2', linewidth=2)
plt.plot(x, exponential_func(x), label='Exponential: e^(0.1x)', linewidth=2)

plt.xlabel('x')
plt.ylabel('y')
plt.title('Multiple Function Plots')
plt.legend()
plt.grid(True, alpha=0.3)

plt.show()

Key Points

  • np.linspace() creates evenly spaced points for smooth curves
  • Use descriptive function names and add labels for clarity
  • The function must accept NumPy arrays and return compatible output
  • Configure plot properties like color, linewidth, and grid for better visualization

Conclusion

Plotting user-defined functions in Python is straightforward with Matplotlib. Define your function with def, generate data points with NumPy, and use plt.plot() to visualize the results.

Updated on: 2026-03-25T23:16:01+05:30

75K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements