64. matplotlib绘图
多轴绘制
图层原理
matplotlib的图层
图层可分为四种
- Canvas层 画布层 位于最底层,用户一般接触不到。
matplotlib.pyplot
就是一个canvas层 - Figure层 图像层 建立在Canvas之上。
plt.figure()
就是一个figure层 - Axes层 坐标层 建立在Figure之上。
fig.add_axes(ax)
就加一个Axes层ax
在figure上,这时就可以画出一个空白的坐标了。 - plot层 绘制层 坐标轴、图例等辅助信息层以及图像层都是建立在Axes之上
实现方法
使用twin()
合并图例-方法1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49#!/usr/bin/env python
# coding=utf-8
import random
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# generate data
x = np.arange(0, 30, 0.5)
y1 = [5.23 * i + random.randint(-10, 10) for i in x]
y2 = [6.12 * i * i + random.randint(-5, 5) * i + random.randint(-19, 29) for i in x]
y3 = [i * i * i + random.randint(-10, 20) for i in x]
# format
matplotlib.rcParams["font.size"] = 20
matplotlib.rcParams["font.family"] = "times new roman"
matplotlib.rcParams["font.style"] = "italic"
# ploting
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x, y1, color="#8ECFC9", marker="o", linestyle="--", label="y1 legend")
# ax1右轴隐藏
# ax1.spines["right"].set_visible(False)
ax1.set_xlabel("x [units]")
ax1.set_ylabel("y1 axis")
# 创建与轴群ax1共享x轴的轴群ax2
ax2 = ax1.twinx()
ax2.plot(x, y2, color="#FFBE7A", marker="o", linestyle=":", label="y2 legend")
ax2.set_ylabel("y2 axis")
ax2.spines['left'].set_position(("axes", 1))
ax2.spines['right'].set_position(("axes", 1))
ax3 = ax2.twinx()
ax3.plot(x, y3, color="#FA7F6F", marker="o", linestyle=":", label="y3 legend")
ax3.set_ylabel("y3 axis")
# 确定ax3轴群右边轴的位置在数值 3
ax3Pos = x.max() + 3
ax3.spines['right'].set_position(('data', ax3Pos))
# 图例位置不对,已经出界,需要使用bbox_to_anchor和bbox_transform设置, 若修改位置, 则修改 bbox_to_anchor
fig.legend(loc=1, bbox_to_anchor=(1, 1), bbox_transform=ax1.transAxes)
plt.show()合并图例方法2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')
time = np.arange(10)
temp = np.random.random(10)*30
Swdown = np.random.random(10)*100-10
Rn = np.random.random(10)*100-10
fig = plt.figure()
ax = fig.add_subplot(111)
lns1 = ax.plot(time, Swdown, '-', label = 'Swdown')
lns2 = ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
lns3 = ax2.plot(time, temp, '-r', label = 'temp')
# added these three lines
lns = lns1+lns2+lns3
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc=0)
ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.savefig('0.png')
rcParams 详解
matplotlibrc 默认文件
1 | #### MATPLOTLIBRC FORMAT |
绘图风格
查看可用的绘图风格
1 | import matplotlib.pyplot as plt |
使用绘图风格
1 | import matplotlib.pyplot as plt |