本文章主要汇总我在科研绘图过程中的遇到的一些问题,主要内容分为三个部分:python matplotlib 绘图过程中多子图设置的问题
python matplotlib 保存图像失真且不是矢量图的问题
python matplotlib savefig保存图片时保存不完整的问题
在之后的科研工作中,我会在安全验证 - 知乎www.zhihu.com
专栏下 持续更新python相关的一系列问题,欢迎大家关注我的专栏。
1、python matplotlib 绘图过程中多子图设置的问题
python中多子图的绘制一般有以下几种不同方法:通过plt.axes直接给定绘图区域的范围
plt.axes的可选参数表示[left, bottom, width, height]。在图形坐标系中,其范围从图的左下角的0到图的右上角的1。
例如:plt.axes([0.65, 0.65, 0.2, 0.2])表示从宽度的65%和图的高度的65%开始,轴的大小是宽度的20%和图的高度的20%。
2.通过plt.subplot函数在网格中一次创建单个网格,可以在整个绘图过程中多次创建
plt.subplot(221)是plt.subplot(2,2,1)另一个写法而已,更完整的写法是plt.subplot(nrows=2, ncols=2, index=1)
# 使用plt.subplot创建小图. plt.subplot(221)表示将整个图像窗口分为2行2列, 当前位置为1.
plt.subplot(221)
# plt.subplot(222)表示将整个图像窗口分为2行2列, 当前位置为2.
plt.subplot(222)# 第一行的右图
# plt.subplot(223)表示将整个图像窗口分为2行2列, 当前位置为3.
plt.subplot(223)
# plt.subplot(224)表示将整个图像窗口分为2行2列, 当前位置为4.
plt.subplot(224)
3.通过plt.subplots函数在网格中一次性创建整个网格
fig.ax= plt.subplots()等价于fig, ax = plt.subplots()
fig, axes = plt.subplots(23):即表示一次性在figure上创建成2*3的网格,使用plt.subplot()只能一个一个的添加
fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')
plt.subplots常用方式如下:
fig, ax = plt.subplots(figsize=(9,6))
fig.subplots_adjust(left=0, bottom=0.1, right=1, top=1, wspace=0.0, hspace=0.25)
其中,subplots_adjust中给定图像的位置[左侧0%,高度0%,向右100%,高度100%,子图宽度间隔0%,子图高度间隔25%]
4.通过plt.gridspec函数绘制跨越多行多列的子图
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
plt.figure()
gs=gridspec.GridSpec(3,3)#分为3行3列
ax1=plt.subplot(gs[0,:])
ax1=plt.subplot(gs[1,:2])
ax1=plt.subplot(gs[1:,2])
ax1=plt.subplot(gs[-1,0])
ax1=plt.subplot(gs[-1,-2])
2、python matplotlib 保存图像模糊失真且不是矢量图的问题
在使用python的matplotlib绘图的过程中,如果使用plt.show( )函数将图像显示出来,然后右键保存到本地,这种方法保存的图像会失真且不是矢量图。
可以使用savfig(fname, dpi=300 )函数保存为矢量图,防止图像失真。
savfig( )函数官方资料可以查看:matplotlib.pyplot.savefig - Matplotlib 3.3.2 documentationmatplotlib.org
其中涉及到矢量图保存的参数主要是:fname, 文件名称 / format, 文件格式
如果在fname进行图像文件命名的时候就设置了文件格式,可以省略format参数。
savfig函数保存图像时,支持的格式包括:.eps, .jpeg, .jpg, .pdf, .pgf, .png, .ps, .raw, .rgba, .svg, .svgz, .tif, .tiff。dpi, the resolution in dots per inch (每英寸点的分辨率)
一般来说,图像的dpi设置为300,折现图的dpi设置为600。
具体的dpi可根据个人要求,一般为1200/ 600/ 300。
3、python matplotlib savefig保存图片时保存不完整的问题
在使用matplotlib绘图时,可能是因为colorbar占据图像的右边位置等问题,导致输出图片偏左。
只需要在画图的时候使用plt.tight_layout()就可以解决这个问题,tight_layout会自动调整子图参数,使之填充整个图像区域。
matplotlib.pyplot.tight_layout函数官方介绍如下:matplotlib.pyplot.tight_layout - Matplotlib 3.1.2 documentationmatplotlib.org
如果在多子图且子图之间宽度间隔设为0%的情况下,或者是子图中colorbar位于子图外部的情况下,使用plt.tight_layout()函数会改变间隔。
此时可以在fig.savefig(fname,dpi=200,bbox_inches = 'tight')中加入bbox_inches = 'tight',此时就可以完美解决这一问题。