matplotlib.pyplot 是一个函数集合,使 matplotlib 能够像 MATLAB 一样进行绘图。每一个 pyplot 函数都会改变 figure,比如创建figure,在figure中创建绘图区域,在绘图区域绘制线条,添加 labels 等。matplotlib.pyplot 的函数调用会记住当前的状态,从而更新 figure 和 绘图区域。而且 matplotlib.pyplot 是直接在当前 axes 进行绘图。
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()
你可能会疑惑,为什么x轴的范围是 0-3,而y轴的范围是 1-4呢?这是因为你只传递了一个列表给 plot 命令,plot命令假设这是 y 的值,并且为你自动产生了 x 的值与之匹配。由于 python 中是以 0 开始的,所以产生的 x 的值也是以 0 开始的,而且长度和 y 序列的长度相同。
你可以传递任何随机数据给 plot 命令,比如同时传入 x, y
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
对于每一个x,y 参数对都有一些可选参数用来设置 线形 和 颜色。而且这种设置方式和 MATLAB 非常相似,而且你也可以将 线形 和 颜色 放在同一个字符串中,比如 'ro',默认值为 'b-'(即蓝色实线)。如果要绘制红色的圆,可以执行以下命令:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.axis([0, 6, 0, 20])
plt.show()
此例中 axes 命令的参数是设置 轴视图 的 xy轴上下限。
当然 matplotlib 也可以和 MATLAB一样,一次绘制多条线
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0., 5., 0.2)
# 分别设置位红色虚线,蓝色正方形,绿色三角形
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()
控制线的属性
线有很多属性可以设置,比如 linewidth,dash style,antialiased等,具体可以查看 Line2D [注1]。
通常有以下几种方式可以设置线属性:
plt.plot(x, y, linewidth=2.0)
line1, line2 = plot(x1, y1, x2, y2)。
下面 假设只绘制一条线,因此使用元组来解包,从而获得列表中的第一个元素,即 lineline, = plt.plot(x, y, '-')
line.set_antialiased(False) # 关闭抗锯齿
lines = plt.plot(x1, y1, x2, y2)
# 使用关键词参数
plt.setp(lines, color='r', linewidth=2.0)
# 或使用类似 MATLAB 的参数值对
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)
设置方法很多,但是强烈推荐使用第二种方法,因为当有多条线的时候可以很明确的指出更改哪一条线的属性。
可以使用 setp 命令获取支持更改的线属性列表
lines = plt.plot([1, 2, 3])
plt.setp(lines)
alpha: float
animated: [True | False]
antialiased or aa: [True | False]
...snip
多个 figure 和 axes 图形绘制
MATLAB 和 pyplot 都有当前figure 和 当前 axes 的概念,而且所有的绘图操作都指向当前 axes。gca 函数可以返回 当前 axes,gcf 函数可以返回 当前 figure。通常你不需要关心这些,因为这些操作都是在后台完成的。
下面创建两个子图:
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)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()
figure 命令是可选的,因为默认情况下执行的就是 figure(1)。如果你不指定任何 axes 的话,默认情况下会创建 subplots(111)。subplots 命令指定 numrows,numcols,fignum,其中 fignum从1到 numrows*numcols,如果 numrows*numcols < 10 的话,逗号是可选的,否则三个数之间要有逗号分隔。如果你不想创建长方形网格,可以使用 axes 命令来指定 axes 的位置,比如 axes([left, bottom,width, height]),所有的值都在 [0, 1] 之间。
你也可以使用多个 figure 命令来创建多个 figures,每一个 figure 都可以包含多个 axes 和 subplots。
import matplotlib.pyplot as plt
plt.figure(1) # 图1
plt.subplot(211) # 图1中的第1个子图
plt.plot([1, 2, 3])
plt.subplot(212) # 图1中第2个子图
plt.plot([4, 5, 6])
plt.figure(2) # 图2
plt.plot([4, 5, 6]) # 默认创建一个子图
plt.figure(1)
plt.subplot(211)
plt.title('Easy as 1, 2, 3')
你可以使用 clf 函数清除当前 figure,使用 cla 清除当前 axes。
添加 text
text 命令可以添加文本到任何位置。xlabel(),ylabel(),title()命令可以添加 text 到指定位置 [注2]。
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(19680801)
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()
所有的 text 方法都会返回 matplotlib.text.Text
实例,就和之前的 line 一样。你也可以传递关键词参数给 text 函数或使用 setp 命令设置属性,更多属性[注3]。
任何文本表达式中都可以使用 TeX 方程表达式。例如在标题中写入表达式:
,使用 $ 符号将其围起来。
plt.title(r'$\sigma_i=15$')
字符串前的 r 非常重要,这是为了说明字符串是原始字符串,而不转义 \ 。matplotlib 有内置的 TeX 表达式解析器和排版引擎,而且使用自带的数学字体。关于如何写数学表达式的信息可以查看 [注4],因此你可以跨平台使用数学文本而不用安装TeX。当然你也可以使用 LaTeX 格式化文本并合并到图中或直接保存 postscript (仅适用于下列 backend:Agg,PS,PDF) [注5]。
text 命令的基本作用就是放置文本到axes任意位置。通常使用时是为了注释图中的一些特征,annotate 函数更容易实现注释功能。此外,有两个点要考虑,分别是 xy 坐标和 文本坐标,即xytext参数,两个参数值均为 (x, y)元组。
import numpy as np
import matplotlib.pyplot as plt
ax = plt.subplot(111)
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)
plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05),
)
plt.ylim(-2,2)
plt.show()
此例中,xy 的位置(arrow tip)和 xytext (text location) 的位置都是在 data 坐标系中。当然还有很多坐标系可以选择 [注6-7]。
对数及其它非线性轴
pyplot 不仅支持 线性刻度,也支持对数刻度 和 logit 刻度。当数据跨度多个量级时可使用对数刻度,而且改变轴刻度的方式非常简单:
plt.xscale(‘log’)
plt.yscale('log')
下面展示使用相同数据,不同的x,y轴刻度进行绘图:
import numpy as np
import matplotlib.pyplot as plt
# 对于 `logit` 刻度非常有用
from matplotlib.ticker import NullFormatter
np.random.seed(19680801)
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))
plt.figure(1)
# linear
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)
# log
plt.subplot(222)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)
# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.01)
plt.title('symlog')
plt.grid(True)
# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
# 使用 `NullFormatter` 格式化y 轴tick label 位空,避免有太多 labels
plt.gca().yaxis.set_minor_formatter(NullFormatter())
# 调整布局,放置 logit 间距太大
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
wspace=0.35)
plt.show()
注1:http://matplotlib.org/api/lines_api.html#matplotlib.lines.Line2D
注2:http://matplotlib.org/users/text_intro.html#text-intro
注3:http://matplotlib.org/users/text_props.html#text-properties
注4:http://matplotlib.org/users/mathtext.html#mathtext-tutorial
注5:http://matplotlib.org/users/usetex.html#usetex-tutorial
注6:http://matplotlib.org/users/annotations.html#annotations-tutorial
注7:http://matplotlib.org/users/annotations.html#plotting-guide-annotation
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有