目录
1. 1 使用 plt.subplots 绘制均匀状态下的子图
导入需要的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号
1 子图
1. 1 使用 plt.subplots
绘制均匀状态下的子图
返回元素分别是画布和子图构成的列表,第一个数字为行,第二个为列,不传入时默认值都为1
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()
subplots
是基于OO模式的写法,显式创建一个或多个axes对象,然后在对应的子图对象上进行绘图操作。
还有种方式是使用subplot
这样基于pyplot模式的写法,每次在指定位置新建一个子图,并且之后的绘图操作都会指向当前子图,本质上subplot
也是Figure.add_subplot
的一种封装。
在调用subplot
时一般需要传入三位数字,分别代表总行数,总列数,当前子图的index
plt.figure()
# 子图1
plt.subplot(2,2,1)
plt.plot([1,2], 'r')
# 子图2
plt.subplot(2,2,2)
plt.plot([1,2], 'b')
#子图3
plt.subplot(224) # 当三位数都小于10时,可以省略中间的逗号,这行命令等价于plt.subplot(2,2,4)
plt.plot([1,2], 'g');
除了常规的直角坐标系,也可以通过projection
方法创建极坐标系下的图表
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')
plt.scatter(theta, r, c=colors, s=area, cmap='hsv', alpha=0.75);
【极坐标的坐标不是x,y,而是theita(角度)和r(半径)】
【关键是在subplot中设置projection = 'polar' 或者polar=True】
1.2 使用 GridSpec
绘制非均匀子图
所谓非均匀包含两层含义:
- 指图的比例大小不同但没有跨行或跨列
- 指图为跨列或跨行状态
利用 add_gridspec
可以指定相对宽度比例 width_ratios
和相对高度比例参数 height_ratios
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()
在上面的例子中出现了 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('样例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()
2 子图上的方法
补充介绍一些子图上的方法
常用直线的画法为: axhline(水平),axvline(垂直),axline(任意方向)
2.1 axhline
函数功能: 在轴上添加一条水平线
函数语法:axhline(y=0, xmin=0, xmax=1, **kwargs)
函数参数:
y:浮点型,默认值0,水平线在坐标中y点的位置
xmin(水平线的起始位置):浮点型,默认值为0,取值位于[0,1]之间,取值0时在图的左边界,取值1时在图的右边界。
xmax(水平线的结束位置):浮点型,默认值为1,取值位于[0,1]之间,0取值时在图的左边界,取值1时在图的右边界。
**kwargs:其他关键参数,如:水平线的颜色、风格、粗细等
2.2 axvline
函数功能:在轴上添加一条垂直线
函数语法:axhline(x=0, xmin=0, ymax=1, **kwargs)
函数参数:
x:浮点型,默认值0,垂直线在坐标中x点的位置
ymin(垂直线的起始位置):浮点型,默认值为0,取值位于[0,1]之间,取值0时在图的下边界,取值1时在图的上边界。
ymax(垂直线的结束位置):浮点型,默认值为1,取值位于[0,1]之间,取值0时在图的下边界,取值1时在图的上边界。
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]);
使用 grid
可以加灰色网格
fig, ax = plt.subplots(figsize=(4,3))
ax.grid(True)
使用 set_xscale
可以设置坐标轴的规度(指对数坐标等)
fig, axs = plt.subplots(1, 2, figsize=(10, 4))
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')
else:
pass
fig.tight_layout()
3 思考题
3.1 墨尔本1981年至1990年的每月温度情况
path = r'存放的文件路径'
df = pd.read_csv(path)
df['Year'] = pd.to_datetime(df['Time']).dt.year
df['Month'] = pd.to_datetime(df['Time']).dt.month
fig,axes = plt.subplots(2,5,figsize =(20,6),sharex=True,sharey=True)
fig.suptitle('墨尔本1981年至1990年月温度曲线',size = 15)
n=0
m=0
m1= 0
for i ,j in df.groupby('Year'):
if m <= 4:
axes[0][m].set_title('{}年'.format(i),size=10)
axes[0][m].plot(j['Month'],j['Temperature'],marker='o',color = 'red')
axes[0][m].grid(True)
m += 1
else:
axes[1][m1].set_title('{}年'.format(i),size=10)
axes[1][m1].plot(j['Month'],j['Temperature'],marker='o')
axes[1][m1].set_xticks(range(1,13))
axes[1][m1].grid(True)
m1 += 1