matplotlib

显示

1
2
%matplotlib tk  # 在GUI中显示
%matplotlib inline # 行内显示, 默认是行内显示

颜色,标记, 线形

  • LineStyle 线形
  • LineWidth 线宽
  • Color 颜色
  • Marker 标记点的形状
  • Label 图例的标签

刻度, 标题, 标签和图例

  • legend, 为了展示每个数据对应的图像名称和数据结构, 生成默认图例
  • xlabel/ylabel, 设置x/y轴标签
  • title, 设置标题
  • xlim/ylim, 控制图标的范围
  • xticks/yticks, 控制图标的刻度
  • gca, 获取当前坐标轴信息
  • spines, 设置边框
  • set_color, 设置边框颜色

中文显示问题

1
2
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

x1 = [1,2,3]
y1 = [5,7,4]
x2 = [1,2,3]
y2 = [10,14,12]

plt.plot(x1, y1, 'ro--', label="1st line")
plt.plot(x2, y2, 'b-', label="2nd line")
plt.xlabel('月份')
plt.ylabel('年份')
plt.xlim(1,3)
plt.ylim(0,15)
plt.xticks(np.linspace(0, 6, 5))
plt.yticks(np.arange(1, 15, 3), ['2011年', '2012年', '2013年', '2014年', '2015年'])
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
plt.legend()
plt.show()

subplot子图

figure对象下边创建一个或多个subplot对象(即axes)用于绘制图像

subplot(numRows, numCols, plotNum)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

x1 = [1,2,3]
y1 = [5,7,4]
x2 = [1,2,3]
y2 = [10,14,12]

plt.subplot(221)
plt.plot(x1, y1, 'r-')
plt.subplot(224)
plt.plot(x2, y2, 'b--')
plt.show()

面向对象的形式

1
2
fig = plt.figure()  # figure实例, 可以添加axes实例
ax = fig.add_subplot(111) # 返回axes实例, 参数1是子图的总行数, 参数2是子图的总列数, 参数3是子图的位置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False

fig = plt.figure(figsize=(8, 6))
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)

ax1.plot(np.random.randn(50).cumsum(), 'g-')
ax2.plot(np.random.randn(50).cumsum(), 'b--')
ax3.plot(np.random.randn(50).cumsum(), 'k--')

plt.show()

subplots

返回一个图像和多个子图
参数: nrows=x, ncols=x, sharex=True, sharey=False, gridspec_kw={‘height_ratios’:[2, 2, 1, 1]}

fig, ax = plt.subplots(2, 2), 参数表示子图的行数和列数, 总共2 * 2个子图, 函数返回一个fig图像和一个子图ax的array列表.

e.g.1

1
2
3
4
5
6
7
8
9
10
11
12
13
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=1, sharex=True, sharey=False)

print(dir(fig))
fig.suptitle('test', fontsize=20)

axes[0].plot(range(10), 'ro-')
axes[1].plot(range(10), 'bo-')
axes[2].plot(range(10), 'go-')
axes[3].plot(range(10), 'mo-')

plt.show()

e.g.2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False

fig, axes = plt.subplots(2, 2)

for i in range(2):
for j in range(2):
axes[i, j].hist(np.random.randn(100), 10, color='g', alpha=0.75)
fig.subplots_adjust(wspace=0, hspace=0)
plt.show()

图像保存文件

plt.savefit(文件名称)

matplotlib柱状图

1
2
matplotlib.pyplot.bar(*args, **kwargs)
bar(x, height, width, bottom, *args, align='center', **kwargs)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import matplotlib.pyplot as plt
import matplotlib as mpl

mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False

plt.figure()
plt.bar([1,3,5,7,9,11], [5,2,7,8,2,6], label="xxoo", color='y')
plt.bar([2,4,6,8,10,12], [8,6,2,5,6,3], label="ooxx", color='g')

plt.legend()
plt.xlabel('bar number')
plt.ylabel('bar height')

plt.title('hello')
plt.show()

matplotlib直方图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
plt.hist(x, 100, normed=1, facecolor='g', alpha=0.75)
plt.title('直方图')
plt.text(60, 0.025, r'$\mu=100, \ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()

matplotlib散点图

1
2
3
4
5
6
7
8
9
10
11
12
import matplotlib.pyplot as plt
import numpy as np

x = [1, 2, 3, 4, 5, 6, 7, 8]
y = [5, 2, 4, 2, 1, 4, 5, 2]
T = np.random.rand(8) * 125
plt.scatter(x, y, label='散点分布', c=T, s=25, marker='o', alpha=0.5)
plt.xlabel('x')
plt.ylabel('y')
plt.title('散点图')
plt.legend()
plt.show()

参考