python matplotlib入门(一)Matplotlib工作流程

  Matplotlib 是一个 Python 的 2D绘图库,它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形 。通过 Matplotlib,开发者可以仅需要几行代码,便可以生成绘图,直方图,功率谱,条形图,错误图,散点图等。在matplotlib中使用最多的模块就是pyplot,pyplot非常接近Matlab的绘图实现,而且大多数的命令与Matlab类似。 从今天起呢, matplotlib将作为我的博客笔记的一个系列,将以我的思路持续更新matplotlib的学习历程, 大致需要更新10次。

  第一篇就简要概括一下matplotlib的几种工作流程,这和matlab还是很相似的,可以对照学习。

matplotlib WorkFlow

plt.plot

import matplotlib.pyplot as plt
import numpy as np


t1 = np.arange(0.0, 1.0, 0.01)

for n in [1, 2, 3, 4]:
    plt.plot(t1, t1**n, label="n=%d"%(n,))

plt.ylabel('values')

plt.axis([0, 1, 0, 1])  # 设置坐标轴范围
# plt.axis 注意与plt.xlim区分, 后者可用于翻转刻度,如x轴 5-->0

leg = plt.legend(loc='best', ncol=2, mode="expand", shadow=True, fancybox=True)
leg.get_frame().set_alpha(0.5)

# latex写法
# plt.title(r'$\alpha_i > \beta_i$', fontsize=20)
# plt.text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20)

plt.savefig('test.png')
plt.show()

这里写图片描述

plt.subplot

import numpy as np
import matplotlib.pyplot as plt

def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)

plt.figure(1)
ax1 = plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')

ax2 = plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()

这里写图片描述

plt.subplots

import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
from numpy.random import multivariate_normal

data = np.vstack([
    multivariate_normal([10, 10], [[3, 2], [2, 3]], size=100000),
    multivariate_normal([30, 20], [[2, 3], [1, 3]], size=1000)
])

gammas = [0.8, 0.5, 0.3]

# 特别注意该种用法, 体现出matlib的原生特点
fig, axes = plt.subplots(nrows=2, ncols=2)

axes[0, 0].set_title('Linear normalization')
axes[0, 0].hist2d(data[:, 0], data[:, 1], bins=100)

for ax, gamma in zip(axes.flat[1:], gammas):
    ax.set_title('Power law $(\gamma=%1.1f)$' % gamma)
    ax.hist2d(data[:, 0], data[:, 1],
              bins=100, norm=mcolors.PowerNorm(gamma))

fig.tight_layout()

plt.show()

这里写图片描述

add_subplot

x = np.arange(0, 10, 0.2)
y = np.sin(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)
plt.show()

小技巧

# Format the minor tick labels of the y-axis into empty strings with
# `NullFormatter`, to avoid cumbering the axis with too many labels.

plt.gca().yaxis.set_minor_formatter(NullFormatter())

# Adjust the subplot layout, because the logit one may take more space
# than usual, due to y-tick labels like "1 - 10^{-3}"
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
                    wspace=0.35)

小结 (重点)

  上面所列举的四个常见WorkFlow其实分为两大类, 一大类是类似于Matlab命令式的绘图方式;另一大类是面向对象的绘图方式。前两种属于Matlab命令式绘图;后两种属于面向对象绘图。pyplot API属于前者,通常它不如面向对象的API灵活,其大多数函数调用也可以作为Axes对象中的方法调用。所以,推荐的学习方法是,了解matplotlib绘图原理,然后推荐大多数场景使用面向对象的绘图方式,这样可以使代码更加简洁明了,便于维护。

猜你喜欢

转载自blog.csdn.net/jeffery0207/article/details/81252790