matplotlib 布局
子图
plt.subplots均匀子图
fig, axs = plt.subplots(2, 5, figsize=(10, 4), sharex=True, sharey=True)
-
返回元素分别是画布和子图构成的列表,
-
第一个数字为行,第二个为列
-
figsize
参数可以指定整个画布的大小 -
sharex
和sharey
分别表示是否共享横轴和纵轴刻度 -
tight_layout
函数可以调整子图的相对大小使字符不会重叠
fig, axs = plt.subplots(2, 5, figsize=(10, 4), sharex=True, sharey=True)
fig.suptitle('样例1', size=20)
for i in range(2):
for j in range(5):
axs[i][j].scatter(np.random.randn(10), np.random.randn(10))
axs[i][j].set_title('第%d行,第%d列'%(i+1,j+1))
axs[i][j].set_xlim(-5,5)
axs[i][j].set_ylim(-5,5)
if i==1: axs[i][j].set_xlabel('横坐标')
if j==0: axs[i][j].set_ylabel('纵坐标')
fig.tight_layout()
⭐极坐标系plt.subplot
没有s
plt.subplot(projection="polar")
N = 150
r = 2 * np.random.rand(N)
theta = 2 * np.pi * np.random.rand(N)
area = 200 * r**2
colors = theta
plt.subplot(projection='polar') # 要用subplot
plt.scatter(theta, r, c=colors, s=area, cmap='hsv', alpha=0.75)
# cmap: 配色方案
# c:color
# s: scale
# alpha:透明度
fig.add_gridspec非均匀子图
所谓非均匀包含两层含义,第一是指图的比例大小不同但没有跨行或跨列,第二是指图为跨列或跨行状态
spec = fig.add_gridspec(nrows, ncols, width_ratios, height_ratios)
width_ratios
可以指定相对宽度比例height_ratios
相对高度比例参数
搭配ax = fig.add_subplot(spec[i,j])
图的比例大小不同
fig = plt.figure(figsize=(10, 4))
spec = fig.add_gridspec(nrows=2, ncols=5, width_ratios=[1,2,3,4,5], height_ratios=[1,3])
fig.suptitle('样例2', size=20)
for i in range(2):
for j in range(5):
ax = fig.add_subplot(spec[i, j])
ax.scatter(np.random.randn(10), np.random.randn(10))
ax.set_title('第%d行,第%d列'%(i+1,j+1))
if i==1: ax.set_xlabel('横坐标')
if j==0: ax.set_ylabel('纵坐标')
fig.tight_layout()
跨行跨列
fig = plt.figure(figsize=(10, 4))
spec = fig.add_gridspec(nrows=2, ncols=6, width_ratios=[2,2.5,3,1,1.5,2], height_ratios=[1,2])
fig.suptitle('样例3', size=20)
# sub1
ax = fig.add_subplot(spec[0, :3])
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub2
ax = fig.add_subplot(spec[0, 3:5])
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub3
ax = fig.add_subplot(spec[:, 5])
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub4
ax = fig.add_subplot(spec[1, 0])
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub5
ax = fig.add_subplot(spec[1, 1:5])
ax.scatter(np.random.randn(10), np.random.randn(10))
fig.tight_layout()
子图上的方法
常用线图、直方图、散点图、条形图、饼图
在 ax
对象上定义了和 plt
类似的图形绘制函数,常用的有: plot, hist, scatter, bar, barh, pie
fig, ax = plt.subplots(figsize=(4,3))
ax.plot([1,2],[2,1])
各种直线
常用直线的画法为: axhline, axvline, axline
(水平、垂直、任意方向
fig, ax = plt.subplots(figsize=(4,3))
ax.axhline(0.5,0.2,0.8)
ax.axvline(0.5,0.2,0.8)
ax.axline([0.3,0.3],[0.7,0.7])
灰色网格
fig, ax = plt.subplots(figsize=(4,3))
ax.grid(True)
坐标轴的规度(指对数坐标等)、标题、轴名
set_xscale
set_title
set_xlabel
fig, axs = plt.subplots(1, 2, figsize=(10, 4))
fig.suptitle('大标题', size=20)
for j in range(2):
axs[j].plot(list('abcd'), [10**i for i in range(4)])
if j==0:
axs[j].set_yscale('log')
axs[j].set_title('子标题1')
axs[j].set_ylabel('对数坐标')
else:
axs[j].set_title('子标题1')
axs[j].set_ylabel('普通坐标')
fig.tight_layout()
文本,注释,箭头
annotate
arrow
text
fig, ax = plt.subplots()
ax.arrow(0, 0, 1, 1, head_width=0.03, head_length=0.05, facecolor='red', edgecolor='blue')
ax.text(x=0, y=0,s='这是一段文字', fontsize=16, rotation=70, rotation_mode='anchor', color='green')
ax.annotate('这是中点', xy=(0.5, 0.5), xytext=(0.8, 0.2), arrowprops=dict(facecolor='yellow', edgecolor='black'), fontsize=16)
图例legend
fig, ax = plt.subplots()
ax.plot([1,2],[2,1],label="line1")
ax.plot([1,1],[1,2],label="line1")
ax.legend(loc=1)
loc
参数如下:
string | code |
---|---|
best | 0 |
upper right | 1 |
upper left | 2 |
lower left | 3 |
lower right | 4 |
right | 5 |
center left | 6 |
center right | 7 |
lower center | 8 |
upper center | 9 |
center | 10 |
练习:
-
墨尔本1981年至1990年的每月温度情况
ex1['year']=ex1['Time'].apply(lambda x:x.split("-")[0])
ex1['month']=ex1['Time'].apply(lambda x:str(int(x.split("-")[1])))
ex1 = ex1.set_index('year')
fig, axs = plt.subplots(2,5, figsize=(16,4),sharex=True,sharey=True)
fig.suptitle("墨尔本1981年至1990年月温度曲线",size=13)
year = 1981
for i in range(2):
for j in range(5):
axs[i,j].plot(ex1.loc[str(year)]['month'],ex1.loc[str(year)]['Temperature'],marker='^',ms=4)
axs[i,j].set_title("%d年"% year,size=10)
axs[i,j].set_ylabel("气温")
year+=1
fig.tight_layout()
- 画出数据的散点图和边际分布
- 用
np.random.randn(2, 150)
生成一组二维数据,使用两种非均匀子图的分割方法,做出该数据对应的散点图和边际分布图
ex2 = np.random.randn(2, 150)
fig = plt.figure(figsize=(8,8))
spec = fig.add_gridspec(nrows=2, ncols=2, width_ratios=[4,1], height_ratios=[1,4]) #可设置wspace=0.05, hspace=0.05 使用tight_layout()
ax1 = fig.add_subplot(spec[1,0])
ax1.scatter(ex2[0],ex2[1])
ax1.grid(True)
ax2 = fig.add_subplot(spec[0,0],sharex=ax1)
ax2.hist(ex2[0], rwidth=5)
ax2.axis('off')
ax2.spines['top'].set_visible(False)
ax2.spines['right'].set_visible(False)
ax2.spines['bottom'].set_visible(False)
ax2.spines['left'].set_visible(False)
ax3 = fig.add_subplot(spec[1,1],sharey=ax1)
ax3.hist(ex2[1], orientation='horizontal')
ax3.axis('off')
ax3.spines['top'].set_visible(False)
ax3.spines['right'].set_visible(False)
ax3.spines['bottom'].set_visible(False)
ax3.spines['left'].set_visible(False)
fig.tight_layout()