前言
官网:
http://matplotlib.org/
学习方式:从官网examples入门学习
http://matplotlib.org/examples/index.html
http://matplotlib.org/gallery.html
子图—matplotlib调整绘图格式
Matplotlib的可以把很多张图画到一个显示界面,在作对比分析的时候非常有用。
对应的有plt的subplot和figure的add_subplo的方法,参数可以是一个三位数字(例如111),也可以是一个数组(例如[1,1,1]),3个数字分别代表
- 子图总行数
- 子图总列数
- 子图位置
1. 使用 plt.subplots 绘制均匀状态下的子图
在一个图表中,绘制多个散点图。
import matplotlib.pyplot as plt
import numpy as np
fig, axs = plt.subplots(2, 5, figsize=(10, 4), sharex=True, sharey=True)
fig.suptitle('demo1',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('x_axis')
if j==0: axs[i][j].set_ylabel('y_axis')
fig.tight_layout()
plt.show()
在一个图表中,绘制多中图表。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# author: chenqionghe
# 画第1个图:折线图
x=np.arange(1,100)
plt.subplot(221)
plt.plot(x,x*x)
# 画第2个图:散点图
plt.subplot(222)
plt.scatter(np.arange(0,10), np.random.rand(10))
# 画第3个图:饼图
plt.subplot(223)
plt.pie(x=[15,30,45,10],labels=list('ABCD'),autopct='%.0f',explode=[0,0.05,0,0])
# 画第4个图:条形图
plt.subplot(224)
plt.bar([20,10,30,25,15],[25,15,35,30,20],color='b')
plt.show()
2.使用 GridSpec 绘制非均匀子图
import matplotlib.pyplot as plt
import numpy as np
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('demo2', 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('X')
if j==0: ax.set_ylabel('Y')
fig.tight_layout()
plt.show()
#在上面的例子中出现了 spec[i, j] 的用法,事实上通过切片就可以实现子图的合并而达到跨图的共能
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('demo3', 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()
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# author: chenqionghe
# 画第1个图:折线图
x=np.arange(1,100)
plt.subplot(221)
plt.plot(x,x*x)
# 画第2个图:散点图
plt.subplot(222)
plt.scatter(np.arange(0,10), np.random.rand(10))
# 画第3个图:饼图
plt.subplot(223)
plt.pie(x=[15,30,45,10],labels=list('ABCD'),autopct='%.0f',explode=[0,0.05,0,0])
# 画第3个图:条形图
# 前面的两个图占了221和222的位置,如果想在下面只放一个图,得把前两个当成一列,即2行1列第2个位置
plt.subplot(212)
plt.bar([20,10,30,25,15],[25,15,35,30,20],color='b')
plt.show()