分享

Matplotlib使用(2)

 云深无际 2021-11-03

pyplot简介

matplotlib.pyplot是使matplotlib像MATLAB一样工作的命令样式函数的集合。每个pyplot功能都会对图形进行一些更改:例如,创建图形,在图形中创建绘图区域,在绘图区域中绘制一些线条,用标签装饰绘图等。

在matplotlib.pyplot各种状态下,函数调用之间会保留在一起,以便跟踪当前图形和绘图区域之类的内容,并且绘图功能指向当前轴

注意

Pyplot API通常不如Python的API灵活。您在此处看到的大多数函数调用也可以被称为Axes对象的方法。我们建议浏览教程和示例以了解其工作原理。

使用pyplot生成可视化效果非常快:


import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()

您可能想知道为什么x轴的范围是0-3,而y轴的范围是1-4。如果为plot()命令提供单个列表或数组 ,则matplotlib假定它是y值的序列,并自动为您生成x值。由于python范围从0开始,因此默认x向量的长度与y相同,但从0开始。因此x数据为 [0, 1, 2, 3]

plot()是一个通用命令,它将接受任意数量的参数。例如,要绘制x与y的关系,可以发出以下命令:

plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

格式化绘图样式

对于每对x,y参数,都有一个可选的第三个参数,它是表示图的颜色和线条类型的格式字符串。格式字符串的字母和符号来自MATLAB,您将颜色字符串与线条样式字符串连接在一起。默认格式字符串是“ b-”,这是一条蓝色实线。例如,要用红色圆圈绘制以上内容,您将绘出

plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro')
plt.axis([0, 6, 0, 20])
plt.show()

axis()上面示例中的 命令采用一个列表并指定轴的视口。[xmin, xmax, ymin, ymax]

如果matplotlib仅限于使用列表,则对于数字处理将毫无用处。通常,您将使用numpy数组。实际上,所有序列都在内部转换为numpy数组。下面的示例说明了使用数组在一条命令中绘制几行具有不同格式样式的行。

import numpy as np

# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)

# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()

用关键字字符串绘图

在某些情况下,您拥有某种格式的数据,该格式允许您使用字符串访问特定变量。例如,使用 numpy.recarraypandas.DataFrame

Matplotlib允许您为此类对象提供data关键字参数。如果提供的话,您可以使用与这些变量相对应的字符串生成图。

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()

用分类变量绘图

也可以使用分类变量创建图。Matplotlib允许您将类别变量直接传递给许多绘图函数。例如:

names = ['group_a', 'group_b', 'group_c']
values = [1, 10, 100]

plt.figure(figsize=(9, 3))

plt.subplot(131)
plt.bar(names, values)
plt.subplot(132)
plt.scatter(names, values)
plt.subplot(133)
plt.plot(names, values)
plt.suptitle('Categorical Plotting')
plt.show()

控制线特性

线条具有许多可以设置的属性:线宽,破折号样式,抗锯齿等;matplotlib.lines.Line2D有几种设置线属性的方法

  • 使用关键字args:

    plt.plot(x, y, linewidth=2.0)
  • 使用Line2D实例的setter方法plot返回Line2D对象列表例如在下面的代码中,我们假设只有一行,所以返回的列表的长度为1。我们使用tuple unpacking 来获取该列表的第一个元素:line1, line2 = plot(x1, y1, x2, y2)line,

    line, = plt.plot(x, y, '-')
    line.set_antialiased(False) # turn off antialiasing
  • 使用setp()命令。下面的示例使用MATLAB样式的命令在行列表上设置多个属性。setp与对象列表或单个对象透明地工作。您可以使用python关键字参数或MATLAB样式的字符串/值对:

    lines = plt.plot(x1, y1, x2, y2)
    # use keyword args
    plt.setp(lines, color='r', linewidth=2.0)
    # or MATLAB style string value pairs
    plt.setp(lines, 'color', 'r', 'linewidth', 2.0)

以下是一些常用得2D属性

英文不难,自己翻译一下

要获取可设置的线属性的列表,请setp()以一条或多条线作为参数来调用该 函数

In [69]: lines = plt.plot([1, 2, 3])

In [70]: plt.setp(lines)
alpha: float
animated: [True | False]
antialiased or aa: [True | False]
...snip

使用多个图形和轴

MATLAB和和pyplot具有当前图形和当前轴的概念。所有绘图命令均适用于当前轴。该函数gca()返回当前轴(一个matplotlib.axes.Axes实例),并 gcf()返回当前图形(一个matplotlib.figure.Figure实例)。通常,您不必为此担心,因为所有这些操作都是在后台进行的。下面是创建两个子图的脚本。

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()
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)它将默认创建,就像subplot(111) 如果您不手动指定任何轴将默认创建一样。该 subplot()命令指定其中范围从1到 如果命令中的逗号是可选的因此与相同numrows, numcols, plot_numberplot_numbernumrows*numcolssubplotnumrows*numcols<10subplot(211)subplot(2, 1, 1)

您可以创建任意数量的子图和轴。如果要手动放置轴(即不在矩形网格上),请使用axes()命令,该命令允许您将位置指定为所有值均位于小数(0至1)坐标中。

您可以通过使用多个figure()具有递增数字的呼叫来创建多个数字 当然,每个图形都可以包含您内心所希望的多个轴和子图:

import matplotlib.pyplot as plt
plt.figure(1) # the first figure
plt.subplot(211) # the first subplot in the first figure
plt.plot([1, 2, 3])
plt.subplot(212) # the second subplot in the first figure
plt.plot([4, 5, 6])


plt.figure(2) # a second figure
plt.plot([4, 5, 6]) # creates a subplot(111) by default

plt.figure(1) # figure 1 current; subplot(212) still current
plt.subplot(211) # make subplot(211) in figure1 current
plt.title('Easy as 1, 2, 3') # subplot 211 title

您可以使用清除当前图形,使用清除clf() 当前轴cla()如果您发现在后台为您维护状态(特别是当前图像,图形和轴)很烦人.

如果要制作大量图形,则还需要注意一件事:在使用图形明确关闭图形之前,图形所需的内存不会完全释放 close()删除对图形的所有引用,和/或使用窗口管理器杀死图形在屏幕上出现的窗口是不够的,因为pyplot会一直保持内部引用直到close() 被调用。

使用文本

text()命令可用于在任意位置添加文本xlabel(),, ylabel()title() 可用于在指示的位置添加文本.

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

# the histogram of the data
n, bins, patches = plt.hist(x, 50, density=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实例。与上面的几行一样,您可以通过将关键字参数传递到文本函数中或使用来自定义属性setp()

t = plt.xlabel('my data', fontsize=14, color='red')

这些属性将在“ 文本”属性和布局中更详细地介绍

在文本中使用数学表达式

matplotlib在任何文本表达式中接受TeX方程表达式。例如写表达式σi=15σi=15 在标题中,您可以编写一个带有美元符号的TeX表达式:

plt.title(r'$\sigma_i=15$')

r之前的标题字符串是很重要的-这意味着该字符串是一个原始的字符串,而不是治疗反斜线作为蟒蛇逃脱。matplotlib具有内置的TeX表达式解析器和布局引擎,并附带了自己的数学字体

.因此,您可以跨平台使用数学文本,而无需安装TeX。对于安装了LaTeX和dvipng的用户.

注释文字

text()上面基本命令的使用将文本放置在轴上的任意位置。文本的常见用法是注释绘图的某些功能,并且该 annotate()方法提供了帮助程序功能以简化注释。在注释中,有两点需要考虑:由参数表示的要注释xy的位置和text的位置xytext这两个参数都是元组。(x, y)

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(箭头尖端)和xytext 位置(文本位置)都在数据坐标中。可以选择多种其他坐标系.

对数轴和其他非线性轴

matplotlib.pyplot不仅支持线性轴刻度,还支持对数和对数刻度。如果数据跨多个数量级,则通常使用此方法。更改轴的比例很容易:

plt.xscale('log')

下面显示了四个图的示例,这些图的y轴数据相同且比例不同。

from matplotlib.ticker import NullFormatter # useful for `logit` scale

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

# make up some data in the open interval (0, 1)
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))

# plot with various axes scales
plt.figure()

# 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)
# 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)

plt.show()

关注我

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约