Home > Article > Backend Development > Matplotlib image saving secrets revealed
Matplotlib image saving skills revealed, specific code examples are needed
Matplotlib is a Python library for drawing charts and graphics, providing rich drawing functions. Matplotlib is widely used in data analysis, scientific research, and visualization applications. Compared to displaying images directly on the terminal, saving images as files makes it easier to share and display them with others. This article will introduce you to some commonly used Matplotlib image saving techniques and provide specific code examples.
import matplotlib.pyplot as plt # 绘制图表 plt.plot([1, 2, 3, 4, 5], [2, 4, 6, 8, 10]) # 保存为PNG格式 plt.savefig('plot.png') # 保存为JPG格式,可以指定dpi参数设置图片的分辨率 plt.savefig('plot.jpg', dpi=300)
import matplotlib.pyplot as plt # 绘制图表 plt.plot([1, 2, 3, 4, 5], [2, 4, 6, 8, 10]) # 保存为PDF格式 plt.savefig('plot.pdf')
import matplotlib.pyplot as plt # 绘制图表 plt.plot([1, 2, 3, 4, 5], [2, 4, 6, 8, 10]) # 保存为SVG格式 plt.savefig('plot.svg')
figure
function to set the image size and resolution. The following is a sample code for setting the image size and resolution: import matplotlib.pyplot as plt # 创建一个10英寸宽、5英寸高的图像 fig = plt.figure(figsize=(10, 5)) # 绘制图表 plt.plot([1, 2, 3, 4, 5], [2, 4, 6, 8, 10]) # 保存为PNG格式,设置dpi参数为300 plt.savefig('plot.png', dpi=300)
set_axis_bgcolor
and set_frame_on
methods of the ##axes object can be implemented. The following is a sample code for setting the image border and background color:
import matplotlib.pyplot as plt # 绘制图表 plt.plot([1, 2, 3, 4, 5], [2, 4, 6, 8, 10]) # 获取当前的axes对象 ax = plt.gca() # 设置背景色为灰色 ax.set_axis_bgcolor('lightgray') # 关闭图像边框 ax.set_frame_on(False) # 保存为PNG格式 plt.savefig('plot.png')
The above is the detailed content of Matplotlib image saving secrets revealed. For more information, please follow other related articles on the PHP Chinese website!