matplotlib

  1. matplotlib 类似 面向对象的 matlab (有点时候似乎没有charts类漂亮….)
  2. 工具: ipython notebook
1
jupyter notebook
  1. 中文显示
1
2
3
4
5
#-*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

HBK普通图 HBK高级图 英文参考

冒泡排序

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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# ref: http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
fig.suptitle("BubbleSort")
ax = plt.axes(xlim=(0, 30), ylim=(0, 100))
X = np.arange(30)
Y = np.random.rand(30) * 100
print Y
fun = plt.bar(X, Y, width = 0.2, facecolor = '#9999ff', edgecolor = 'white');

line, = ax.plot([], [], lw=2)


# initialization function: plot the background of each frame
def init():
fun = plt.bar(X, Y, width=0.2, facecolor='#9999ff', edgecolor='white');
return fun


# animation function. This is called sequentially
# note: i is framenumber
def update(i):
for y in range(30 - i - 1):
if Y[y] < Y[y + 1]:
Y[y], Y[y + 1] = Y[y + 1],Y[y]
plt.clf()
fig.suptitle("BubbleSort_FAST")
fun = plt.bar(X, Y, width=0.2, facecolor='#9999ff', edgecolor='white');
return fun


# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, update, init_func=init,
frames=30, interval=20, blit=False)

plt.show()

可以创建多个子图像,多个(坐标轴, 标题, 标签, 刻度, 刻度label)

可以加上legend(图例)

连点

1
2
3
4
5
from matplotlib import pyplot as plt
x = [1,2,3,1]
y = [1,3,0,1]
plt.plot(x,y)
plt.grid(True, color = 'r')

样式图例

画图——样式

数据线的样式设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
颜色缩写    全称
b blue
c cyan
g gree
k black
m magenta
r red
w white
y yellow


线型缩写 含义
-- --虚线
-. -.虚线
: .虚线
- 实线

marker类型参考
http://www.labri.fr/perso/nrougier/teaching/matplotlib/#line-properties

HBK代码

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

x = [1,2,3,1]
y = [1,3,0,1]

# np.array将列表转换成numpy的数组后可以支持广播broadcast运算
plt.plot(x,y,color='r',linewidth='2',linestyle='--',marker='D', label='one')
plt.plot(np.array(x)+1,np.array(y)+1,color='g',linewidth='3',linestyle=':',marker='o', label='two')
plt.plot(np.array(x)+2,np.array(y)+3,color='k',linewidth='1',linestyle='-.',marker='>', label='three')

plt.grid(True)
plt.legend()
#plt.legend(loc='upper left')

plt.show()

公式TeX, 文本和标注

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import matplotlib.pyplot as plt
fig = plt.figure() #figsize=(10,6)
ax= fig.add_subplot(111)
ax.set_xlim([1, 6]);
ax.set_ylim([1, 9]);
ax.text(2, 8, r"$ \mu \alpha \tau \pi \lambda \omega \tau \
lambda \iota \beta $",color='r',fontsize=20);

ax.text(2, 6, r"$ \lim_{x \rightarrow 0} \frac{1}{x} $",fontsize=20);
ax.text(2, 4, r"$ a \ \leq \ b \ \leq \ c \ \Rightarrow \ a \
\leq \ c$",fontsize=20);

ax.text(2, 2, r"$ \sum_{i=1}^{\infty}\ x_i^2$",fontsize=20);
ax.text(4, 8, r"$ \sin(0) = \cos(\frac{\pi}{2})$",fontsize=20);
ax.text(4, 6, r"$ \sqrt[3]{x} = \sqrt{y}$",fontsize=20);
ax.text(4, 4, r"$ \neg (a \wedge b) \Leftrightarrow \neg a \
\vee \neg b$");

ax.text(4, 2, r"$ \int_a^b f(x)dx$",fontsize=20);
plt.show()

pie

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#-*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.figure(figsize=(9,6))

labels = [u'直接访问', u'外部链接', u'搜索引擎']
sizes = [12,15,30]
colors = ['yellowgreen', 'gold', 'lightskyblue']

explode = (0.05, 0.0, 0.0)
patches, l_texts, p_texts = plt.pie(sizes, explode=explode, labels=labels, colors=colors, labeldistance=0.8,autopct='%3.lf%%', shadow=True, startangle= 90, pctdistance=0.6)
plt.axis('equal')
plt.show()

Bar

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#-*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
plt.figure(figsize=(9,6))

n = 12
X = np.arange(n) + 1;

Y1 = (1- X/float(n+1)) * np.random.uniform(0.5,1.0,n)
Y2 = (1- X/float(n+1)) * np.random.uniform(0.5,1.0,n)

width = 0.5
#plt.barh(X, Y1, facecolor = '#9999ff', edgecolor = 'white')

plt.bar(X, Y1, width=width, facecolor = '#9999ff', edgecolor = 'white')
plt.bar(X+width, Y2, width=width, facecolor = '#ff9999', edgecolor = 'white')

plt.show()

动画

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
#!/usr/bin/python 
# -*- coding: utf-8 -*-
# CopyRight by heibanke

from matplotlib import pyplot as plt
import matplotlib.animation as animation
import numpy as np


def update_point(num):
fig_points.set_data(data[:, 0:num])
return fig_points,

fig1 = plt.figure()

num_point = 50
data = np.random.rand(2, num_point)
fig_points, = plt.plot([], [], 'ro')

plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xlabel('x')
plt.title('Scatter Point')

# interval
# repeat
# frames
# fargs
# init_func
anim = animation.FuncAnimation(fig1, update_point,num_point)

#anim = animation.FuncAnimation(fig1, update_point,frames=num_point, interval=50, blit=False, repeat=False)

plt.show()

"""
def init():
fig_points.set_data([],[])
return fig_points,

anim = animation.FuncAnimation(fig1, update_point,frames=num_point, init_func=init, interval=50, blit=False, repeat=False)

anim.save("anim1.mp4")
anim.save('anim1.gif', writer='imagemagick')
"""

文章目录
  1. 1. 冒泡排序
  2. 2. 连点
  3. 3. 样式图例
    1. 3.1. 画图——样式
    2. 3.2. HBK代码
  4. 4. 公式TeX, 文本和标注
  5. 5. pie
  6. 6. Bar
  7. 7. 动画