利用 Matplotlib 绘制数据图形(一)

什么是 Matplotlib ? Matplotlib 可以做什么?

Matplotlib 是一个用于 Python 的绘图库。借助 Matplotlib, 几行代码就能绘制出高质量的数据图形。

import matplotlib.pyplot as plt
import numpy as np

# Fixing random state for reproducibility
np.random.seed(19680801)

N = 100
r0 = 0.6
x = 0.9 * np.random.rand(N)
y = 0.9 * np.random.rand(N)
area = (20 * np.random.rand(N))**2  # 0 to 10 point radii
c = np.sqrt(area)
r = np.sqrt(x * x + y * y)
area1 = np.ma.masked_where(r < r0, area)
area2 = np.ma.masked_where(r >= r0, area)
plt.scatter(x, y, s=area1, marker='^', c=c)
plt.scatter(x, y, s=area2, marker='o', c=c)
# Show the boundary between the regions:
theta = np.arange(0, np.pi / 2, 0.01)
plt.plot(r0 * np.cos(theta), r0 * np.sin(theta))

plt.show()
复制代码

绘图部分仅用了5行代码 * 案例来自官方文档

Matplotlib 的设计理念

Matplotlib 使用层级结构来组织事物。Matplotlib 的最上层是 「state-machine environment」,它控制着绘图的具体内容,比如线条、颜色、文字等。接着是第一层面向对象接口,通过这一层可以创建和追踪绘图区域。最后是将 Matplotlib 视为整体与其它应用进行交互的接口。

我理解的 Matplotlib 层级结构

上图是我理解的 Matplotlib 层级结构,不一定正确。但是这个理解让我在使用 Matplotlib 时顺畅无阻。注意其中的 Axes 不是字面意思「axis 的复数」,而是指一个包含坐标的图形。Figure 是指一整张大的绘图区域。我们可以在一个 Figure 里绘制多个不同的 Axes。

fig,(ax1,ax2) = plt.subplots(1,2)
ax1.set_title('axes 1')
ax2.set_title('axes 2')
fig.suptitle('one figure, two axes')
复制代码

Matplotlib 实际使用前应该知道的细节

来自 官方文档的 figure 组成,很重要

大部分时候我们的数据,格式是 pandas 中的 DataFrame 或者 numpy 中的 Matrix,但是官方说了:使用这两种格式绘制图形,结果不一定符合预期。np.array 和 np.ma.masked_array 才是期望的数据类型。所以,np.martix 和 pd.DataFrame 需要转换为 np.array:

# convert a dataframe
a = pandas.DataFrame(np.random.rand(4,5), columns = list('abcde'))
a_asndarray = a.values
# convert a matrix
b = np.matrix([[1,2],[3,4]])
b_asarray = np.asarray(b)
复制代码

手动转换数据类型并不是必须的,对于 numpy.recarray 和 pandas.DataFrame,我们可以直接使用变量名作为绘图时的输入。

data = pd.DataFrame({
    'a':[1,2,3],
    'b':[1,4,9]
})
fig,ax_1 = plt.subplots()
ax_1.scatter('a', 'b', data=data)
复制代码

也可以一次传入多对数据,在同一张图中绘制多个同类图形。

x = np.array([1,2,3])
plt.plot(x,x,x,x**2,x,x**3)
复制代码

如何简单方便的开始使用 Matplotlib

对我而言,在 jupyter notebook 中使用 Matplotlib 是一种非常容易且直观的方式,也是我最为青睐的方式。 关于 jupyter notebook 的安装网络上有很多教程,我个人推荐安装 miniconda 后再在 miniconda 中安装 jupyter notebook。

因为 Matplotlib 可以在很多环境中使用,所以官方的安装文档也很详细,但是对于初学者就不太友好了。如果使用 jupyter notebook ,直接在 miniconda 中 conda install matplotlib 就可以开始体验 Matplotlib 了。

另外,你或许会接触到 seaborn,ggpy 等绘图库。ggpy 三年没更新了,弃坑为妙。seaborn 是在 Matplotlib 上做的更高层次封装,基本上 seaborn 和 Matplotlib 要混合使用才能实现微调图形细节。所以用 seaborn 也得了解 Matplotlib。

你可能感兴趣的:(python,开发工具)