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 retrieve the list of supported file formats for Matplotlib savefig()function?
To retrieve the list of supported file formats for Matplotlib's savefig() function, we can use the get_supported_filetypes() method. This is useful when you want to programmatically check which formats are available for saving plots.
Using get_supported_filetypes()
The get_supported_filetypes() method returns a dictionary where keys are file extensions and values are format descriptions ?
import matplotlib.pyplot as plt
# Get current figure and access canvas
fig = plt.gcf()
supported_formats = fig.canvas.get_supported_filetypes()
# Display all supported formats
for extension, description in supported_formats.items():
print(f"{extension}: {description}")
eps: Encapsulated Postscript jpg: Joint Photographic Experts Group jpeg: Joint Photographic Experts Group pdf: Portable Document Format pgf: PGF code for LaTeX png: Portable Network Graphics ps: Postscript raw: Raw RGBA bitmap rgba: Raw RGBA bitmap svg: Scalable Vector Graphics svgz: Scalable Vector Graphics tif: Tagged Image File Format tiff: Tagged Image File Format
Practical Example with Plot Saving
Here's how you can use this information to save a plot in different formats ?
import matplotlib.pyplot as plt
import numpy as np
# Create a sample plot
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y, label='sin(x)')
plt.title('Sample Plot')
plt.legend()
# Get supported formats
supported_formats = plt.gcf().canvas.get_supported_filetypes()
# Show available vector formats (good for publications)
vector_formats = ['eps', 'pdf', 'svg', 'ps']
print("Vector formats available:")
for fmt in vector_formats:
if fmt in supported_formats:
print(f" {fmt}: {supported_formats[fmt]}")
plt.show()
Vector formats available: eps: Encapsulated Postscript pdf: Portable Document Format svg: Scalable Vector Graphics ps: Postscript
Common File Formats
| Format | Type | Best For |
|---|---|---|
| PNG | Raster | Web display, presentations |
| Vector | Publications, printing | |
| SVG | Vector | Web graphics, scalable images |
| JPG/JPEG | Raster | Photos, compressed images |
Conclusion
Use get_supported_filetypes() to check available formats before saving plots. Vector formats like PDF and SVG are ideal for publications, while PNG is perfect for web display.
Advertisements
