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 draw a heart with pylab?
Drawing a heart shape with pylab/matplotlib can be achieved using mathematical equations and the fill_between() method. This creates a beautiful heart visualization using parametric equations.
Mathematical Approach
The heart shape is created using two mathematical functions:
- Upper part:
y1 = sqrt(1 - (abs(x) - 1)²) - Lower part:
y2 = -3 * sqrt(1 - (abs(x) / 2)^0.5)
Steps
- Set the figure size and adjust the padding between and around the subplots.
- Create x, y1 and y2 data points using numpy.
- Fill the area between (x, y1) and (x, y2) using
fill_between()method. - Place text on the plot using
text()method at (0, -1.0) point. - To display the figure, use
show()method.
Example
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-2, 2, 1000)
y1 = np.sqrt(1 - (abs(x) - 1) ** 2)
y2 = -3 * np.sqrt(1 - (abs(x) / 2) ** 0.5)
plt.fill_between(x, y1, color='red')
plt.fill_between(x, y2, color='red')
plt.text(0, -1.0, 'Heart', fontsize=24, color='black',
horizontalalignment='center')
plt.show()
Enhanced Heart with Styling
Here's an enhanced version with better styling and axis customization ?
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [8, 6]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-2, 2, 1000)
y1 = np.sqrt(1 - (abs(x) - 1) ** 2)
y2 = -3 * np.sqrt(1 - (abs(x) / 2) ** 0.5)
plt.fill_between(x, y1, color='crimson', alpha=0.8)
plt.fill_between(x, y2, color='crimson', alpha=0.8)
plt.text(0, -1.5, 'Love You', fontsize=20, color='darkred',
horizontalalignment='center', fontweight='bold')
plt.axis('equal')
plt.axis('off')
plt.title('Heart Shape with Matplotlib', fontsize=16, pad=20)
plt.show()
Key Parameters
| Parameter | Purpose | Example Value |
|---|---|---|
x range |
Controls heart width | -2 to 2 |
color |
Heart color | 'red', 'crimson' |
alpha |
Transparency | 0.8 |
fontsize |
Text size | 20, 24 |
Conclusion
Creating a heart shape with matplotlib involves using mathematical functions and the fill_between() method. You can customize colors, transparency, and text to create beautiful romantic visualizations for special occasions.
Advertisements
