今天來講一下昨天遺留下來的問題———plt.tight_layout()的作用。
tight英文翻譯過來是緊的意思,tight_layout也是就固定佈局的意思。
爲什麼需要固定佈局呢?參考官方文檔http://matplotlib.org/users/tight_layout_guide.html。
學習機器學習一定要多參考官方文檔,不知道的東西自己試一試就知道了。
下面是結合官方文檔的教學。
When you have multiple subplots, often you see labels of different axes overlapping each other.
翻譯過來:
就是當你有很多的子圖的時候,你的子圖的lable可能會重疊起來。
什麼是重疊起來呢?看下面圖片:
所以plt.tight_layout()函數就是綁定佈局,防止因爲拉伸佈局而使得lable重疊起來。
參考官方的代碼改成的例子。
去掉了一些我們還沒有學習的函數【因爲有和沒有基本沒有區別。】
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : SundayCoder-俊勇
# @File : figure6.py
import matplotlib.pyplot as plt
import numpy as np
def example_plot(ax, fontsize=12):
ax.plot([1, 2])
ax.set_xlabel('x-label', fontsize=fontsize)
ax.set_ylabel('y-label', fontsize=fontsize)
ax.set_title('Title', fontsize=fontsize)
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
plt.show()
這個運行結果就會出現第一幅圖片中lable重疊的效果。
黑魔法來了,使用plt.tight_layout()。
在plt.show()這句代碼之前加上plt.tight_layout()
。
效果立即不一樣【你可以自己拉伸試一下】
得到的就是一個比較好的效果。
爲了方便,還是把代碼全貼出來:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : SundayCoder-俊勇
# @File : figure6.py
import matplotlib.pyplot as plt
import numpy as np
def example_plot(ax, fontsize=12):
ax.plot([1, 2])
ax.set_xlabel('x-label', fontsize=fontsize)
ax.set_ylabel('y-label', fontsize=fontsize)
ax.set_title('Title', fontsize=fontsize)
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
plt.tight_layout()
plt.show()