Python中的 Matplotlib.figure.Figure.set_tight_layout()
Matplotlib是Python中的一个库,它是 NumPy 库的数值数学扩展。 figure 模块提供了顶级 Artist,即 Figure,其中包含所有绘图元素。该模块用于控制所有绘图元素的子图和顶级容器的默认间距。
matplotlib.figure.Figure.set_tight_layout() 方法
matplotlib库的set_tight_layout()方法figure模块用于设置绘制时是否调用tight_layout以及如何调用。
Syntax: set_tight_layout(self, tight)
Parameters: This method accept the following parameters that are discussed below:
- tight : This parameters contains the boolean value or dict with keys “pad”, “w_pad”, “h_pad”, “rect” or None.
Returns: This method does not returns any value.
下面的示例说明了 matplotlib.figure 中的 matplotlib.figure.Figure.set_tight_layout()函数:
示例 1:
# Implementation of matplotlib function
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-5, 5, 0.01)
y1 = -3*x*x + 10*x + 10
y2 = 3*x*x + x
fig, ax = plt.subplots()
fig.tight_layout()
ax.plot(x, y1, x, y2, color='black')
ax.fill_between(x, y1, y2,
where = y2 >y1,
facecolor = 'green',
alpha = 0.8)
ax.fill_between(x, y1, y2,
where = y2 <= y1,
facecolor = 'black',
alpha = 0.8)
fig.set_tight_layout(True)
fig.canvas.draw()
fig.suptitle("""matplotlib.figure.Figure.set_tight_layout()
function Example\n\n""",fontweight="bold")
plt.show()
输出:
示例 2:
# Implementation of matplotlib function
import matplotlib.pyplot as plt
import matplotlib.tri as mtri
import numpy as np
# Create triangulation.
x = np.asarray([0, 1, 2, 3,
0.5, 1.5,
2.5, 1, 2,
1.5])
y = np.asarray([0, 0, 0, 0,
1.0, 1.0, 1.0,
2, 2, 3.0])
triangles = [[0, 1, 4], [1, 5, 4],
[2, 6, 5], [4, 5, 7],
[5, 6, 8], [5, 8, 7],
[7, 8, 9], [1, 2, 5],
[2, 3, 6]]
triang = mtri.Triangulation(x, y, triangles)
z = np.cos(1.5 * x) * np.cos(1.5 * y)
fig, axs = plt.subplots()
axs.tricontourf(triang, z)
axs.triplot(triang, 'go-', color ='white')
fig.tight_layout(rect =(0.1, 0.1, 0.95, 0.95))
fig.set_tight_layout(False)
fig.canvas.draw()
fig.suptitle("""matplotlib.figure.Figure.set_tight_layout()
function Example\n\n""", fontweight ="bold")
plt.show()
输出: