Python 绘图库 Matplotlib 代码示例

Line Plot

1
2
3
4
5
6
7
import matplotlib.pyplot as plt

X = range(100)
Y = [value ** 2 for value in X]

plt.plot(X, Y)
plt.show()

line plot

Using Numpy
1
2
3
4
5
6
7
8
import numpy as np
import matplotlib.pyplot as plt

X = np.linspace(0, 2 * np.pi, 100)
Y = np.sin(X)

plt.plot(X, Y)
plt.show()

line with numpy

等同于如下代码:

1
2
3
4
5
6
7
8
9
import 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
2
3
4
5
6
7
8
9
10
import numpy as np
import matplotlib.pyplot as plt

X = np.linspace(0, 2 * np.pi, 100)
Ya = np.sin(X)
Yb = np.cos(X)

plt.plot(X, Ya)
plt.plot(X, Yb)
plt.show()

multiple line plot

从文本文件中读取数据
1
2
3
4
5
6
7
# my_data.txt
0 0
1 1
2 4
4 16
5 25
6 36
1
2
3
4
5
6
7
import numpy as np
import matplotlib.pyplot as plt

data = np.loadtxt('my_data.txt')
plt.plot(data[:, 0], data[:, 1])

plt.show()

file data

等同于如下代码:

1
2
3
4
5
6
7
8
9
10
import 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(1024, 2)
print(data)
# [[0.74566428 0.27225566]
# [0.49387305 0.22290731]
# [0.78644733 0.44918945]
# ...
# [0.42446667 0.31317443]
# [0.06518628 0.21378513]
# [0.85117629 0.83458943]]

plt.scatter(data[:, 0], data[:, 1])
plt.show()

scatter plot

Bar Charts
1
2
3
4
5
6
import matplotlib.pyplot as plt

data = [5., 25., 50., 20.]

plt.bar(range(len(data)), data)
plt.show()

bar charts

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

data = [[5., 25., 50., 20.],
[4., 23., 51., 17.],
[6., 22., 52., 19.]]

X = np.arange(4)
plt.bar(X + 0.00, data[0], color='b', width=0.25)
plt.bar(X + 0.25, data[1], color='g', width=0.25)
plt.bar(X + 0.50, data[2], color='r', width=0.25)

plt.show()

multiple bar charts

Histogram
1
2
3
4
5
6
7
import numpy as np
import matplotlib.pyplot as plt

X = np.random.randn(1000)

plt.hist(X, bins=20)
plt.show()

histogram

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

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')

fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.

plt.show()

pie chart

Color

matplotlib 中定义颜色的方式有以下几种:

  • (R, G, B, A),如 (1.0, 0.0, 0.0) 表示红色,第四项数字 A (可省略)表示透明度
  • 字符 bgrcmykw,分别表示蓝、绿、红、青、洋红、黄、黑、白
  • HTML 颜色字符串 #RRGGBB,如 #FFFFFF 表示纯白色
  • 灰度字符串,介于 0 和 1 之间的浮点数,如 0.75 表示中度浅灰

示例一

1
2
3
4
5
6
7
8
9
10
11
12
import 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()

color

示例二
Iris 文本数据下载自 http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data,格式如下:

1
2
3
4
5
4.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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import numpy as np
import matplotlib.pyplot as plt

label_set = (
b'Iris-setosa',
b'Iris-versicolor',
b'Iris-virginica'
)

# convert label to index number.
# Iris-setosa -> 0, Iris-versicolor -> 1, Iris-virginica -> 2.
def read_label(label):
return label_set.index(label)

data = np.loadtxt('iris.data', delimiter=',',
converters={4: read_label})

color_set = ('b', 'r', 'm')
color_list = [color_set[int(label)] for label in data[:, 4]]

plt.scatter(data[:, 0], data[:, 1], color=color_list)
plt.show()

iris
上面的示例中只用到前两列和最后一列数据,将最后一列数据 label 替换为对应的 index 数字,以便在作图时根据 index 施以不同的着色。

Line Pattern

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

def pdf(X, mu, sigma):
a = 1. / (sigma * np.sqrt(2. * np.pi))
b = -1. / (2. * sigma ** 2)
return a * np.exp(b * (X - mu) ** 2)

X = np.linspace(-6, 6, 1024)

plt.plot(X, pdf(X, 0., 1.), color='r', linestyle='solid')
plt.plot(X, pdf(X, 0., .5), color='g', linestyle='dashed')
plt.plot(X, pdf(X, 0., .25), color='m', linestyle='dashdot')

plt.show()

line style

Marker Style
1
2
3
4
5
6
7
8
9
10
11
12
import 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='m', marker='x', size=100)
plt.scatter(B[:, 0], B[:, 1], color='g', marker='^')
plt.show()

marker style

Title and Label

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

X = np.linspace(-4, 4, 1024)
Y = .25 * (X + 4.) * (X + 1.) * (X - 2.)

plt.title('Power curve for airfoil KV873')
plt.xlabel('Air speed')
plt.ylabel('Total drag')
plt.text(-0.5, -0.25, 'Brackmard minimum')

plt.plot(X, Y, c='k')
plt.show()

label

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

X = np.linspace(0, 6, 1024)
Y1 = np.sin(X)
Y2 = np.cos(X)

plt.xlabel('X')
plt.ylabel('Y')

plt.plot(X, Y1, c='k', lw=3., label='sin(X)')
plt.plot(X, Y2, c='.5', lw=3., ls='--', label='cos(X)')

plt.legend()
plt.show()

legend

Figures

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

T = np.linspace(-np.pi, np.pi, 1024)
grid_size = (4, 2)

plt.subplot2grid(grid_size, (0, 0), rowspan=3, colspan=1)
plt.plot(np.sin(2 * T), np.cos(0.5 * T), c='k')

plt.subplot2grid(grid_size, (0, 1), rowspan=3, colspan=1)
plt.plot(np.cos(3 * T), np.sin(T), c='k')

plt.subplot2grid(grid_size, (3, 0), rowspan=1, colspan=3)
plt.plot(np.cos(5 * T), np.sin(7 * T), c='k')

plt.tight_layout()
plt.show()

subplot2grid

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

np.random.seed(19680801)
data = np.random.randn(2, 100)

fig, axs = plt.subplots(2, 2, figsize=(5, 5))
axs[0, 0].hist(data[0])
axs[1, 0].scatter(data[0], data[1])
axs[0, 1].plot(data[0], data[1])
axs[1, 1].hist2d(data[0], data[1])

plt.show()

subplots

User Interface

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
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.widgets import Slider

def supershape_radius(phi, a, b, m, n1, n2, n3):
theta = .25 * m * phi
cos = np.fabs(np.cos(theta) / a) ** n2
sin = np.fabs(np.sin(theta) / b) ** n3
r = (cos + sin) ** (-1. / n1)
r /= np.max(r)
return r

phi = np.linspace(0, 2 * np.pi, 1024)
m_init = 3
n1_init = 2
n2_init = 18
n3_init = 18

fig = plt.figure()
ax = fig.add_subplot(111, polar=True)
ax_m = plt.axes([0.05, 0.05, 0.25, 0.025])
ax_n1 = plt.axes([0.05, 0.10, 0.25, 0.025])
ax_n2 = plt.axes([0.7, 0.05, 0.25, 0.025])
ax_n3 = plt.axes([0.7, 0.10, 0.25, 0.025])

slider_m = Slider(ax_m, 'm', 1, 20, valinit=m_init)
slider_n1 = Slider(ax_n1, 'n1', .1, 10, valinit=n1_init)
slider_n2 = Slider(ax_n2, 'n2', .1, 20, valinit=n2_init)
slider_n3 = Slider(ax_n3, 'n3', .1, 20, valinit=n3_init)

r = supershape_radius(phi, 1, 1, m_init, n1_init, n2_init, n3_init)
lines, = ax.plot(phi, r, lw=3.)

def update(val):
r = supershape_radius(phi, 1, 1, np.floor(slider_m.val),
slider_n1.val, slider_n2.val, slider_n3.val)
lines.set_ydata(r)
fig.canvas.draw_idle()

slider_n1.on_changed(update)
slider_n2.on_changed(update)
slider_n3.on_changed(update)
slider_m.on_changed(update)

plt.show()

slider

参考资料

matplotlib Plotting Cookbook
Sample plots in Matplotlib