本章节是代码笔记
子图布局
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
ax1 = plt.subplot2grid((3,3),(0,0)) # 3*3的矩阵,在(0,0)位置
ax2 = plt.subplot2grid((3,3),(1,0))
ax3 = plt.subplot2grid((3,3),(0,2),rowspan=3) #占3行
ax4 = plt.subplot2grid((3,3),(2,0),colspan = 2) # 占2列
ax5 = plt.subplot2grid((3,3),(0,1),rowspan=2)
输出结果图:
嵌套图 fig.add_axes() :
x = np.linspace(0,10,1000)
y1 = x**2
y2 = np.sin(x**2)
fig,ax1 = plt.subplots() # s 不能缺少
left,bottom,width,height = [0.22,0.45,0.3,0.35] #设置大小
ax2 = fig.add_axes([left,bottom,width,height])#在ax1中嵌入ax2
ax1.plot(x,y1)
ax2.plot(x,y2)
输出结果图:
还有一种写法 inset_axes()-需要导入这个模块:
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
#导入数据:
top10_arrivals_countries = ['CANADA','MEXICO','UNITED\nKINGDOM',\
'JAPAN','CHINA','GERMANY','SOUTH\nKOREA',\
'FRANCE','BRAZIL','AUSTRALIA']
top10_arrivals_values = [16.625687, 15.378026, 3.934508, 2.999718,\
2.618737, 1.769498, 1.628563, 1.419409,\
1.393710, 1.136974]
arrivals_countries = ['WESTERN\nEUROPE','ASIA','SOUTH\nAMERICA',\
'OCEANIA','CARIBBEAN','MIDDLE\nEAST',\
'CENTRAL\nAMERICA','EASTERN\nEUROPE','AFRICA']
arrivals_percent = [36.9,30.4,13.8,4.4,4.0,3.6,2.9,2.6,1.5]
fig,ax1 = plt.subplots(figsize=(20,12))
data = ax1.bar(range(10),top10_arrivals_values,color='blue')
plt.xticks(range(10),top10_arrivals_countries,fontsize=18)
explode = (0.08, 0.08, 0.05, 0.05,0.05,0.05,0.05,0.05,0.05)
ax2 = inset_axes(ax1,width = 6,height = 6,loc = 5)
ax2.pie(arrivals_percent,labels = arrivals_countries,autopct='%1.1f%%',explode=explode)
for text in texts+autotexts:
text.set_fontsize(16)
for spine in ax1.spines.values():
spine.set_visible(False)
输出结果图: