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

什么是 Matplotlib ? Matplotlib 能够作什么?

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

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行代码 * 案例来自官方文档bash

Matplotlib 的设计理念

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

我理解的 Matplotlib 层级结构dom

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

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 组成,很重要spa

大部分时候咱们的数据,格式是 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,咱们能够直接使用变量名做为绘图时的输入。3d

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

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

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。cdn

由于 Matplotlib 能够在不少环境中使用,因此官方的安装文档也很详细,可是对于初学者就不太友好了。若是使用 jupyter notebook ,直接在 miniconda 中 conda install matplotlib 就能够开始体验 Matplotlib 了。

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

相关文章
相关标签/搜索