Line Plot
1 | import matplotlib.pyplot as plt |
Using Numpy
1 | import numpy as np |
等同于如下代码:1
2
3
4
5
6
7
8
9import math
import matplotlib.pyplot as plt
T = range(100)
X = [(2 * math.pi * t) / len(T) for t in T]
Y = [math.sin(value) for value in X]
plt.plot(X, Y)
plt.show()
Multiple Line Plot
1 | import numpy as np |
从文本文件中读取数据
1 | # my_data.txt |
1 | import numpy as np |
等同于如下代码:1
2
3
4
5
6
7
8
9
10import matplotlib.pyplot as plt
X, Y = [], []
for line in open('my_data.txt', 'r'):
values = [float(s) for s in line.split()]
X.append(values[0])
Y.append(values[1])
plt.plot(X, Y)
plt.show()
其他类型的图形
Scatter Plot
1 | import numpy as np |
Bar Charts
1 | import matplotlib.pyplot as plt |
Multiple Bar Charts
1 | import numpy as np |
Histogram
1 | import numpy as np |
Pie Charts
1 | import matplotlib.pyplot as plt |
Color
matplotlib 中定义颜色的方式有以下几种:
(R, G, B, A)
,如(1.0, 0.0, 0.0)
表示红色,第四项数字 A (可省略)表示透明度- 字符
b
、g
、r
、c
、m
、y
、k
、w
,分别表示蓝、绿、红、青、洋红、黄、黑、白 - HTML 颜色字符串
#RRGGBB
,如#FFFFFF
表示纯白色 - 灰度字符串,介于 0 和 1 之间的浮点数,如 0.75 表示中度浅灰
示例一:1
2
3
4
5
6
7
8
9
10
11
12import numpy as np
import matplotlib.pyplot as plt
A = np.random.standard_normal((100, 2))
A += np.array((-1, -1))
B = np.random.standard_normal((100, 2))
B += np.array((1, 1))
plt.scatter(A[:, 0], A[:, 1], color='.75')
plt.scatter(B[:, 0], B[:, 1], color='y')
plt.show()
示例二:
Iris 文本数据下载自 http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data,格式如下:1
2
3
4
54.6,3.2,1.4,0.2,Iris-setosa
5.3,3.7,1.5,0.2,Iris-setosa
5.0,3.3,1.4,0.2,Iris-setosa
7.0,3.2,4.7,1.4,Iris-versicolor
6.4,3.2,4.5,1.5,Iris-versicolor
1 | import numpy as np |
上面的示例中只用到前两列和最后一列数据,将最后一列数据 label 替换为对应的 index 数字,以便在作图时根据 index 施以不同的着色。
Line Pattern
1 | import numpy as np |
Marker Style
1 | import numpy as np |
Title and Label
1 | import numpy as np |
Legend
1 | import numpy as np |
Figures
1 | import numpy as np |
Subplots
1 | import matplotlib.pyplot as plt |
User Interface
1 | import numpy as np |