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
Save figure as file from iPython notebook using Matplotlib
To save a figure as a file from iPython notebook using Matplotlib, we can use the savefig() method. This method allows you to export plots in various formats like PNG, PDF, SVG, and more.
Basic Steps
To save a figure as a file from iPython, we can take the following steps ?
- Create a new figure or activate an existing figure
- Add an axes to the figure using add_axes() method
- Plot the data
- Save the plot using savefig() method
Example
Here's how to create and save a simple plot ?
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.title("Sample Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.savefig('test.png', bbox_inches='tight')
plt.show()
Different File Formats
You can save plots in various formats by changing the file extension ?
import matplotlib.pyplot as plt
# Create a simple plot
plt.figure(figsize=(8, 4))
plt.plot([1, 2, 3, 4], [10, 20, 15, 25], marker='o')
plt.title("Sales Data")
# Save in different formats
plt.savefig('plot.png', dpi=300, bbox_inches='tight') # PNG
plt.savefig('plot.pdf', bbox_inches='tight') # PDF
plt.savefig('plot.svg', bbox_inches='tight') # SVG
plt.savefig('plot.jpg', dpi=300, bbox_inches='tight') # JPEG
plt.show()
Common savefig() Parameters
| Parameter | Description | Example |
|---|---|---|
dpi |
Resolution in dots per inch | dpi=300 |
bbox_inches |
Controls whitespace around plot | bbox_inches='tight' |
transparent |
Makes background transparent | transparent=True |
facecolor |
Sets background color | facecolor='white' |
Advanced Example with Customization
Here's how to save a plot with custom settings ?
import matplotlib.pyplot as plt
import numpy as np
# Generate sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create and customize plot
plt.figure(figsize=(10, 6))
plt.plot(x, y, 'b-', linewidth=2, label='sin(x)')
plt.title('Sine Wave', fontsize=16)
plt.xlabel('X values', fontsize=12)
plt.ylabel('Y values', fontsize=12)
plt.grid(True, alpha=0.3)
plt.legend()
# Save with high quality settings
plt.savefig('sine_wave.png',
dpi=300, # High resolution
bbox_inches='tight', # Remove extra whitespace
facecolor='white', # White background
edgecolor='none', # No border
transparent=False) # Solid background
plt.show()
Conclusion
Use plt.savefig() to export Matplotlib plots from iPython notebooks. Specify the desired format through file extension and use parameters like dpi=300 and bbox_inches='tight' for high-quality output with minimal whitespace.
Advertisements
