matplotlib绘图笔记

2017-05-09

本篇记录使用matplotlib进行简单的数据可视化。

1. matplotlib 与 pyplot

按照官网的说明:pyplot是matplotlib 的一个module。通常,我们也只是使用这一个module。但是dir(matplotlib)并没有查看到其中包含pyplot,这就让人很好奇了。
matplotlib是一个python libary, pyplot 是一个 module。那么,libary和module, 还有package到底是什么呢?

  • module: a module in python is a .py file that defines one or more function/classes which you intend to reuse in different codes of your program.
    模块:简单的说就是.py文件,我们会把想要重复使用的代码放到module里。使用时直接import。
  • package: a directory of Python module(s).
    包:通常我们把一些相关的module文件组织在一起。dir查看一个package,它一定具有path变量,module则没有。
  • libary: When used in Python, a library is used loosely to describe a collection of the core modules.
    库:libary这种叫法在Python里并不常见,matplotlib其实是一个package,我们在python 的PyPI - the Python Package Index里可以查到它哦。
    现在,我们知道了:matplotlib是一个package,而面向用户的功能主要由其中的pyplot modulet提供,因此我们使用时常常这样写:
1
import matplotlib.pyplot as plt

2. matplotlib 的基本概念

  • figure: 可以理解成画板上的画布,是最最基础的。
  • axes: 画布通常可以划分成多个小的区域,我们在不同区域作画,这些小的区域叫做axes。如果不划分,那么整个画布就是一个绘图区域。
1
2
3
4
5
6
7
8
# 一幅图
fig = plt.figure()
# 多幅图:分成m*n块子图
fig, axes = plt.subplots(m, n)
axes[0].plot(x, y)
# 划分,并切换到第一个子图
plt.subplot(121)
plt.plot(x, y)

3. 使用示例:

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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#!/usr/bin/python
# -*-coding:utf-8-*-
"""learn.py
Description: Learn to use pyplot
Date: 2017-05-08
Author: MonkandMonkey
"""
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
# ============================
# Draw a simple pic
# ============================
def pic1():
# evenly sampled time at 200ms intervals
y = np.arange(0., 10., 1.)
# red dashes, blue squares and green triangles
plt.plot(y, y, 'r--', y, y ** 2, 'bs', y, y ** 3, 'g^')
# x axis range, y axis range
plt.xlim([0, 10])
plt.ylim([0, 1000])
plt.show()
print("Plot pic1: a simple plot with three different markers and colors!")
# ============================
# Draw a pic with text
# ============================
def pic2():
y = np.arange(0, 10, 0.4)
# plot dot
plt.plot(y, 2 * y, "r--", y, y ** 2, "bs")
# add labels
plt.xlabel("no")
plt.ylabel("num")
# add legends
plt.legend(["legend1", "legend2"])
plt.show()
# add tilte
plt.title("Pic2: work with text")
print("Plot pic2: a simple plot with xlabel and ylabel!")
# ============================
# subplots
# ============================
def pic3():
y = np.arange(0, 10, 0.5)
plt.figure()
# m, n, no of axes
plt.subplot(121)
plt.plot(y, y, 'r--', y, y ** 2, 'bs', y, y ** 3, 'g^')
plt.title("sub1")
plt.subplot(122)
plt.plot(y, 2 * y, "r--", y, y ** 2, "bs")
plt.title("sub2")
plt.show()
print("Plot pic3: subplots!")
# ============================
# boxplot
# ============================
def pic4():
data = [{"a": "aaa", "b": 22.3, "c": 20}, {"a": "bbb", "b": 41.2, "c": 2}, {"a": "ccc", "b": 52.22, "c": 5},
{"a": "dddd", "b": 28.9, "c": 19.2}, {"a": "ee", "b": 28.3, "c": 11}]
df = pd.DataFrame(data)
df.set_index(["a"])
y = df["b"]
plt.boxplot(y)
# config
plt.title("pic4: box plot")
plt.show()
# ============================
# histogram
# ============================
def pic5():
fig, ax = plt.subplots()
mu = 50
sigma = 2.5
# normalization rand float 800*1 dim
y = mu + sigma * np.random.randn(800)
n, bins, patches = plt.hist(y, 100, normed=1)
# add a 'best fit' line
y = mlab.normpdf(bins, mu, sigma)
ax.plot(bins, y, '--')
ax.set_xlabel('Smarts')
ax.set_ylabel('Probability density')
ax.set_title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')
plt.show()
print("Pic5: histogram!")
if __name__ == '__main__':
pic5()