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
Display two Sympy plots as one Matplotlib plot (add the second plot to the first)
To display two SymPy plots as one Matplotlib plot, you can combine multiple symbolic expressions into a single visualization. This is useful when comparing functions or showing relationships between different mathematical expressions.
Setting Up the Environment
First, import the necessary modules and configure the plot settings ?
from sympy import symbols from sympy.plotting import plot from matplotlib import pyplot as plt # Set figure size and layout plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True
Creating and Combining Plots
Create two separate SymPy plots and combine them using the extend() method ?
from sympy import symbols
from sympy.plotting import plot
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = symbols('x')
# Create first plot (quadratic function)
p1 = plot(x*x, show=False)
# Create second plot (linear function)
p2 = plot(x, show=False)
# Add all series from p2 to p1
p1.extend(p2)
# Display the combined plot
p1.show()
How It Works
The process involves these key steps:
- symbols('x') − Creates a symbolic variable for mathematical expressions
- plot(expression, show=False) − Creates a plot object without immediately displaying it
- extend() − Adds all data series from the second plot to the first plot
- show() − Renders the final combined plot
Alternative Method: Multiple Expressions
You can also plot multiple functions directly in a single plot command ?
from sympy import symbols
from sympy.plotting import plot
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = symbols('x')
# Plot multiple functions in one command
combined_plot = plot(x*x, x, show=False)
combined_plot.show()
Conclusion
Use the extend() method to combine separate SymPy plots, or pass multiple expressions to plot() directly. Both approaches create unified visualizations for comparing mathematical functions.
Advertisements
