14
Lesson 14
Saving and exporting plots
Objective
By the end of this lesson, students will be able to save and export plots in various file formats (PNG, PDF, SVG, etc.) using the savefig() function in Matplotlib.
1. Introduction to savefig():
Once a plot is created and displayed in Matplotlib, you may want to save it to a file for use in reports, presentations, websites, or further analysis. The savefig() function allows you to save your figure in multiple formats such as PNG, PDF, SVG, and more.
Syntax:
By the end of this lesson, students will be able to save and export plots in various file formats (PNG, PDF, SVG, etc.) using the savefig() function in Matplotlib.
1. Introduction to savefig():
Once a plot is created and displayed in Matplotlib, you may want to save it to a file for use in reports, presentations, websites, or further analysis. The savefig() function allows you to save your figure in multiple formats such as PNG, PDF, SVG, and more.
Syntax:
plt.savefig('filename.format', dpi=resolution, bbox_inches='tight')
- filename.format : The name of the file you want to save, along with the desired format (e.g., plot.png or plot.pdf).
- dpi : The dots-per-inch resolution. Higher dpi values result in better image quality.
- bbox_inches : If set to 'tight', it adjusts the plot size to include all labels and titles without cutting anything off.
2. Saving in different formats:
Matplotlib supports a variety of file formats, including:
- PNG: Lossless format for web graphics.
- PDF: High-quality, scalable format often used for print.
- SVG: Scalable vector graphics, useful for high-quality web illustrations.
- JPG: A compressed format that may reduce quality.
Example: Saving as PNG
import matplotlib.pyplot as plt import numpy as np # Create sample data x = np.linspace(0, 10, 100) y = np.sin(x) # Plot the data plt.plot(x, y) # Save the plot as a PNG file plt.savefig('sine_plot.png') # Display the plot plt.show()
In this example:
- We saved the plot as a PNG image using plt.savefig('sine_plot.png').
- The default resolution (dpi=100) is used here, but it can be customized.
3. Specifying image quality with DPI:
The dpi (dots per inch) parameter controls the resolution of the saved image. A higher dpi means a clearer and sharper image, but it will also increase the file size.
Example: Saving with high resolution
import matplotlib.pyplot as plt import numpy as np # Create sample data x = np.linspace(0, 10, 100) y = np.sin(x) # Plot the data plt.plot(x, y) # Save the plot as a high-resolution PNG file plt.savefig('sine_plot_high_res.png', dpi=300) # Show the plot plt.show()
In this example, we saved the plot with a resolution of
4. Saving as PDF, SVG, and other formats:
Matplotlib allows you to export your plots into various file formats. Here are examples of saving as PDF and SVG:
Example: Saving as PDF
import matplotlib.pyplot as plt import numpy as np # Create sample data x = np.linspace(0, 10, 100) y = np.cos(x) # Plot the data plt.plot(x, y) # Save the plot as a PDF file plt.savefig('cosine_plot.pdf') # Show the plot plt.show()
Saving as a PDF (plt.savefig('cosine_plot.pdf')) is great for reports or high-quality scalable documents.
Example: Saving as SVG
import matplotlib.pyplot as plt import numpy as np # Create sample data x = np.linspace(0, 10, 100) y = np.tan(x) # Plot the data plt.plot(x, y) # Save the plot as an SVG file plt.savefig('tangent_plot.svg') # Show the plot plt.show()
Saving as an SVG (plt.savefig('tangent_plot.svg')) is useful when you need a scalable vector graphic, often used in web design or technical illustrations.
5. Ensuring no overlapping elements (using bbox_inches):
Sometimes, parts of the plot (like labels, legends, or titles) might be cut off when saving. To avoid this, use bbox_inches='tight', which automatically adjusts the plot’s size to fit all elements.
Example: Using bbox_inches to avoid cropping
import matplotlib.pyplot as plt import numpy as np # Create sample data x = np.linspace(0, 10, 100) y = np.sin(x) # Plot the data plt.plot(x, y) plt.title('Sine Wave') plt.xlabel('X-axis') plt.ylabel('Y-axis') # Save the plot ensuring nothing is cut off plt.savefig('sine_wave_tight.png', bbox_inches='tight') # Show the plot plt.show()
In this example, the bbox_inches='tight' parameter ensures that the title and labels are included fully without being cut off.
6. Saving without displaying the plot:
Sometimes, you may want to save a plot without displaying it on the screen (e.g., when generating many plots automatically). You can do this by calling savefig() without plt.show().
Example: Saving without displaying
import matplotlib.pyplot as plt import numpy as np # Create sample data x = np.linspace(0, 10, 100) y = np.sin(x) # Plot the data plt.plot(x, y) # Save the plot without displaying it plt.savefig('sine_plot_no_display.png') # Do not use plt.show() to prevent display
In this case, the plot is saved directly to a file without being shown in a pop-up window.
7. Exercises:
Exercise: 1
1. Create a sine wave plot and save it as a PNG file. Use a resolution of dpi=150.
2. Plot a cosine wave and export the figure as a PDF document.
3. Create a scatter plot with random data and save it as an SVG file.
Exercice: 2
1. Create a plot with a title and axis labels, and save it as a PNG. Use bbox_inches='tight' to make sure the title and labels are fully included.
Exercice: 3
1. Create a plot with multiple lines and save it as a high-resolution PNG (dpi=300) without displaying the plot.
Conclusion
In this lesson, we covered how to save and export plots in different formats using savefig() in Matplotlib. We learned how to control the resolution of saved images, save in formats such as PNG, PDF, and SVG, and ensure that nothing is cut off using bbox_inches. Additionally, we explored how to save plots without displaying them, making Matplotlib suitable for automated workflows or large-scale data visualizations.