Python爬蟲、資料分析、網站開發等案例教程視頻免費在線觀看
https://space.bilibili.com/523606542
Python學習交流群:1039649593
多圖布局
解決元素重疊的問題:
在一個Figure上面,可能存在多個Axes物件,如果Figure比較小,那么有可能會造成一些圖形元素重疊,這時候我們就可以通過fig.tight_layout或者是fig.subplots_adjust方法來幫我們調整,假如現在沒有經過調整,那么以下代碼的效果圖如下:
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,axes = plt.subplots(2,2) fig.set_facecolor("y") example_plot(axes[0,0]) example_plot(axes[0,1]) example_plot(axes[1,0]) example_plot(axes[1,1])
效果圖如下:
為了避免多個圖重疊,可以使用plt.tight_layout來實作:
# 之前的代碼... plt.tight_layout()
效果圖如下:
其中tight_layout還有兩個引數可以使用,分別是w_pad和h_pad,這兩個引數分別表示的意思是在水平方向的圖之間的間距,以及在垂直方向這些圖的間距,
另外也可以通過fig.subplots_adjust(left=None,bottom=None,right=None,top=None,wspace=None,hspace=None)來實作,效果如下:
# 之前的代碼... fig.subplots_adjust(0,0,1,1,hspace=0.5,wspace=0.5)
效果圖如下:
自定義布局方式:
如果布局不是固定的幾宮格的方式,而是某個圖占據了多行或者多列,那么就需要采用一些手段來實作,如果不是很復雜,那么直接可以通過subplot等方法來實作,示例代碼如下:
ax1 = plt.subplot(221) ax2 = plt.subplot(223) ax3 = plt.subplot(122)
效果圖如下:

但是如果實作的布局比較復雜,那么就需要采用GridSpec物件來實作,示例代碼如下:
fig = plt.figure() # 創建3行3列的GridSpec物件 gs = fig.add_gridspec(3,3) ax1 = fig.add_subplot(gs[0,0:3]) ax1.set_title("[0,0:3]") ax2 = fig.add_subplot(gs[1,0:2]) ax2.set_title("[1,0:2]") ax3 = fig.add_subplot(gs[1:3,2]) ax3.set_title("[1:3,2]") ax4 = fig.add_subplot(gs[2,0]) ax4.set_title("[2,0]") ax5 = fig.add_subplot(gs[2,1]) ax5.set_title("[2,1]") plt.tight_layout()
效果圖如下:
也可以設定寬高比例,示例代碼如下:
# 設定寬度比例為1:2:1 widths = (1,2,1) # 設定高度比例為2:2:1 heights = (2,2,1) fig = plt.figure() # 創建GridSpec物件的時候指定寬高的比 gs = fig.add_gridspec(3,3,width_ratios=widths,height_ratios=heights) for row in range(0,3): for col in range(0,3): fig.add_subplot(gs[row,col]) plt.tight_layout()
效果圖如下:

手動設定位置:
通過fig.add_axes的方式添加Axes物件,可以直接指定位置,也可以在添加完成后,通過axes.set_position的方式設定位置,示例代碼如下:
# add_axes的方式 fig = plt.figure() fig.add_subplot(111) fig.add_axes([0.2,0.2,0.4,0.4]) # 設定position的方式 fig,axes = plt.subplots(1,2) axes[1].set_position([0.2,0.2,0.4,0.4])
散點圖和直方圖合并實戰:
fig = plt.figure(figsize=(8,8)) widths = (2,0.5) heights = (0.5,2) gs = fig.add_gridspec(2,2,width_ratios=widths,height_ratios=heights) # 頂部的直方圖 ax1 = fig.add_subplot(gs[0,0]) ax1.hist(male_athletes['Height'],bins=20) for tick in ax1.xaxis.get_major_ticks(): tick.label1On = False # 中間的散點圖 ax2 = fig.add_subplot(gs[1,0]) ax2.scatter('Height','Weight',data=https://www.cnblogs.com/qshhl/p/male_athletes) # 右邊的直方圖 ax3 = fig.add_subplot(gs[1,1]) ax3.hist(male_athletes['Weight'],bins=20,orientation='horizontal') for tick in ax3.yaxis.get_major_ticks(): tick.label1On = False fig.tight_layout(h_pad=0,w_pad=0)
效果圖如下:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/280493.html
標籤:Python
上一篇:Python資料分析入門(二十六):繪圖分析——Tick容器
下一篇:python選擇結構
