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
Exporting an svg file from a Matplotlib figure
To export an SVG file from a matplotlib figure, we can use the savefig() method with the .svg format. SVG (Scalable Vector Graphics) files are ideal for plots as they maintain quality at any zoom level and are perfect for web publishing.
Steps to Export SVG File
Set the figure size and adjust the padding between and around the subplots.
Create a figure and a set of subplots.
Create random x and y data points using numpy.
Plot x and y data points using
plot()method.Save the .svg format file using
savefig()method.
Example
Here's how to create a simple plot and save it as an SVG file ?
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
x = np.random.rand(10)
y = np.random.rand(10)
ax.plot(x, y, ls='dotted', linewidth=2, color='red')
plt.savefig("myimg.svg")
print("SVG file 'myimg.svg' has been created successfully!")
SVG file 'myimg.svg' has been created successfully!
Customizing SVG Export
You can customize the SVG export with additional parameters ?
import numpy as np
import matplotlib.pyplot as plt
# Create sample data
x = np.linspace(0, 10, 50)
y = np.sin(x)
plt.figure(figsize=(8, 4))
plt.plot(x, y, 'b-', linewidth=2, label='sin(x)')
plt.xlabel('X values')
plt.ylabel('Y values')
plt.title('Sine Wave Plot')
plt.legend()
plt.grid(True, alpha=0.3)
# Save with custom settings
plt.savefig("custom_plot.svg",
format='svg',
dpi=300,
bbox_inches='tight')
print("Custom SVG file saved with high DPI and tight bbox!")
Custom SVG file saved with high DPI and tight bbox!
Key Parameters for savefig()
| Parameter | Description | Example |
|---|---|---|
format |
File format | 'svg' |
dpi |
Resolution | 300 |
bbox_inches |
Bounding box | 'tight' |
transparent |
Transparent background | True/False |
Output
When you execute this code, it will create an SVG file called myimg.svg and save it in the current directory. The SVG file can be opened in web browsers or vector graphics software.
Conclusion
Use plt.savefig("filename.svg") to export matplotlib figures as SVG files. SVG format preserves vector quality and is perfect for web publishing and scalable graphics.
