Wednesday, 27 September 2023

How to Save Your Matplotlib Plots in PNG, JPEG, PDF, and More?

Using 'savefig()' method of PyPlot, we can save the plot to a file in various image formats, such as PNG, JPEG, PDF, SVG, and more.

 

Following parameters are supported by saveconfig method.

 

a.   format: Specifies the format of the output file like 'pdf', 'png', 'jpg', 'svg', etc.,

b.   dpi: Sets the resolution of the image in dots/pixels per inch.

c.    box_inches: Specifies the portion of the figure to save. 'tight' ensures that the entire plot is saved without any cutoff.

 

Example

plt.savefig('/Users/Shared/demo.pdf', format='pdf', dpi=350)
plt.close()

 

It is good practice to call the close method to release the resources associated with the figure.


save_plot.py

import matplotlib.pyplot as plt

# Sample data
year = [2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022]
population = [1246.2, 1262.6, 1279.7, 1297.4, 1315.8, 1334.9, 1354.7, 1374.2, 1407.6, 1417.2]

# Create a line plot
plt.plot(year, population)

# Add labels and title
plt.xlabel('Year')
plt.ylabel('Population in Millions')
plt.title('India Population in millions by year wise', verticalalignment='center',
          horizontalalignment='center',  color='blue', fontweight='bold',
          backgroundcolor='lightblue')

# Display the plot
# plt.show()
plt.savefig('/Users/Shared/demo.png')
plt.savefig('/Users/Shared/demo.pdf', format='pdf', dpi=350)

# Call close method to release the resources associated with the figure.
plt.close()

 


  

Previous                                                    Next                                                    Home

No comments:

Post a Comment