matplotlib 学习笔记

本笔记从matplotlib官网教程学习而来, 仅供自己练习之用, 英语还可以的同学, 建议去看官网教程.

In [1]:
import numpy as np
import matplotlib.pyplot as plt
In [4]:
fig = plt.figure()
fig.suptitle('no axes on this page')
fig, ax_list = fig.subplots(2,2)
In [13]:
x = np.array([1,2,3,4])
y = x ** 2
plt.plot(x,y)  # 默认使用蓝色实线 'b-' 绘制
plt.show()
In [14]:
plt.plot(x,y, 'ro') # 使用红色圆点绘制
plt.axis([0,6,0,20])
plt.show()
In [15]:
t = np.arange(0,5, 0.2)
# red dashes, blue square, green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()

Plotting with keyword strings

In [16]:
data = {'a': np.arange(50),
        'c': np.random.randint(0, 50, 50),
        'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100

plt.scatter('a', 'b', c='c', s='d', data=data)
plt.xlabel('entry a')
plt.ylabel('entry b')
plt.show()

Plotting with categorical variables

In [18]:
names = ['group-a', 'group-b', 'group-c']
values = [1, 10, 100]
plt.figure(1, figsize=(9,3))
plt.subplot(1,3, 1)
plt.bar(names, values)
plt.subplot(1,3,2)
plt.scatter(names, values)
plt.subplot(1,3,3)
plt.plot(names, values)
plt.suptitle('categorical plotting')
plt.show()

Working with text

In [28]:
mu,sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
n, bins, patches = plt.hist(x, 50, density=1, facecolor='g', alpha=0.75)
plt.xlabel('Smart', color='white')
plt.ylabel('Probability',color='white')
plt.title('Histogram of IQ', color='white')
plt.axis([40,160, 0, 0.03])
plt.text(60, 0.025, r'$\mu=100,\ \sigma=15$', fontsize=11)
plt.grid(True)
plt.show()

Annotating text

In [31]:
t = np.arange(0, 5, 0.02)
s = np.cos(2 * np.pi * t)
plt.plot(t, s, lw = 2)
plt.annotate('local max', xy=(2,1), xytext=(1, 1.5), 
            arrowprops= dict(facecolor='red', shrink=0.05) ) # 这里不能传入用花括号组成的字典
plt.ylim(-2,2)
plt.show()