Matplotlib学习笔记(第二章 2.12Pyplot教程)

2.1.2 Pyplot教程

pyplot接口的介绍

Pyplot简介

matplotlib.pyplot是一个函数集合,它使matplotlib像MATLAB一样工作。每个pyplot函数对图形做一些更改:例如创建图形,在图形中创建绘图区域,在绘图区域中绘制一些线条,用标签装饰绘图区域,等等。

在matplotlib.pyplot中,不同的状态被保存在函数调用中,因此它可以跟踪当前图形和绘图区域等信息,并且绘图函数被定向到当前的绘图区域。(请注意,这里和文档中的大多数地方的"axes"指的是图形(figure)中的绘图区域,而不是数学术语上的数轴或坐标轴)。


注意:pyplot API通常不如面向对象的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。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])

在这里插入图片描述

输出:

[<matplotlib.lines.Line2D object at 0x7f5effdf1760>]
设置绘图样式的格式

对于每对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
# 以200ms的间隔均匀采样时间
t = np.arange(0., 5., 0.2)
# 红色虚线、蓝色正方形和绿色三角形
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()

在这里插入图片描述

使用关键字字符串绘图

在某些情况下,数据的格式允许使用字符串访问特定变量。例如,使用numpy.recarray或者 pandas.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.line。Line2D有几种设置线属性的方法:

使用关键字args:

plt.plot(x, y, linewidth=2.0)

使用Line2D instance. plot的setter方法,返回Line2D对象的列表;例如,line1,line2 = plot(x1, y1, x2, y2)。在下面的代码中,我们假设只有一条线,因此返回的列表长度为1。我们去除包含线的元组,以获得列表的第一个元素:

line, = plt.plot(x, y, '-')
line.set_antialiased(False) # 关闭反锯齿

使用setp。下面的示例使用matlab样式的函数在列表中设置多个属性。setp透明地处理对象列表或单个对象。您可以使用python关键字参数或MATLAB风格的字符串/值对:

lines = plt.plot(x1, y1, x2, y2)
# 使用关键字参数
plt.setp(lines, color='r', linewidth=2.0)
# 或MATLAB风格的字符串/值对
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)

这里是可用的Line2D属性:

属性值类型
alphafloat
animated[True | False]
antialiased or aa[True | False]
clip_boxa matplotlib.transform.Bbox instance
clip_on[True | False]
clip_patha Path instance and a Transform instance, a Patch
color or cany matplotlib color
containsthe hit testing function
dash_capstyle[‘butt’ |‘round’| ‘projecting’]
dash_joinstyle[‘miter’ |‘round’ |‘bevel’]
dashessequence of on/off ink in points
data(np.array xdata, np.array ydata)
figurea matplotlib.figure.Figure instance
labelany string
linestyle or ls[ ‘-’ | ‘–’ | ‘-.’ |‘:’ | ‘steps’ | …]
linewidth or lwfloat value in points
marker[ ‘+’ | ‘,’ |‘.’ | ‘1’ | ‘2’ | ‘3’ | ‘4’ ]
markeredgecolor or mecany matplotlib color
markeredgewidth or mewfloat value in points
markerfacecolor or mfcany matplotlib color
markersize or msfloat
markevery[ None | integer | (startind, stride) ]
pickerused in interactive line selection
pickradiusused in interactive line selection
solid_capstyle[‘butt’ | ‘round’ | ‘projecting’]
solid_joinstyle[‘miter’ | ‘round’ | ‘bevel’]
transforma matplotlib.transforms.Transform instance
visible[True |False]
xdatanp.array
ydatanp.array
zorderany number

要获取可设置的线的属性的列表,请使用一条线或多条线作为参数调用setp函数:

lines = plt.plot([1, 2, 3])
plt.setp(lines)

运行结果如下:

  agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
  alpha: float or None
  animated: bool
  antialiased or aa: bool
  clip_box: `.Bbox`
  clip_on: bool
  clip_path: Patch or (Path, Transform) or None
  color or c: color
  contains: unknown
  dash_capstyle: {'butt', 'round', 'projecting'}
  dash_joinstyle: {'miter', 'round', 'bevel'}
  dashes: sequence of floats (on/off ink in points) or (None, None)
  data: (2, N) array or two 1D arrays
  drawstyle or ds: {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default'
  figure: `.Figure`
  fillstyle: {'full', 'left', 'right', 'bottom', 'top', 'none'}
  gid: str
  in_layout: bool
  label: object
  linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
  linewidth or lw: float
  marker: marker style string, `~.path.Path` or `~.markers.MarkerStyle`
  markeredgecolor or mec: color
  markeredgewidth or mew: float
  markerfacecolor or mfc: color
  markerfacecoloralt or mfcalt: color
  markersize or ms: float
  markevery: None or int or (int, int) or slice or List[int] or float or (float, float) or List[bool]
  path_effects: `.AbstractPathEffect`
  picker: unknown
  pickradius: float
  rasterized: bool or None
  sketch_params: (scale: float, length: float, randomness: float)
  snap: bool or None
  solid_capstyle: {'butt', 'round', 'projecting'}
  solid_joinstyle: {'miter', 'round', 'bevel'}
  transform: `matplotlib.transforms.Transform`
  url: str
  visible: bool
  xdata: 1D array
  ydata: 1D array
  zorder: float
使用多个图形和轴

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)  # 表示2行1列第1个区域
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')

plt.subplot(212) # 表示2行1列第2个区域
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()

在这里插入图片描述

这里的图形调用是可选的,因为如果不存在图形,就会创建一个图形,就像绘图区域一样。

如果不存在,则创建(等效于显式调用 subplot ( )。子图调用指定numrow、numcols、plot_number,其中的plot_number从1到numrow**numcols。子批调用中的逗号是可选的,如果numrow*numcols<10,那么子图(211)与子图(2,1,1)是相同的。

You can create an arbitrary number of subplots and axes. If you want to place an axes man-ually,i.e., not on a rectangular grid,use axes,which allows you to specify the location asaxes( [left, bottom,width,height]) where all values ar in fractional (0 to 1) coordi-nates. See lgallery/subplots_axes_and_figures/axes_demo for an example of placing axes manually and/gallery/subplots_axes_and_figures subplot_demo for an example with lots of subplots.

您可以创建任意数量的子图和轴。如果你想把一个轴不是在一个矩形的网格上,使用axes,它允许你指定位置axes([left, bottom, width, height]),其中所有的值都是小数(0到1)坐标。

有关手动放置轴的示例,请参阅/gallery/subplots_axes_and_figures/axes_demo。

对于包含大量子图的示例,请参阅/gallery/subplots_axes_and_figures/subplot_demo。

您可以通过使用多个图形调用来创建多个图形,并增加图形的索引。当然,每一个图形都可以包含你的心想要的不论多少绘图区域和子图样式:

import matplotlib.pyplot as plt

plt.figure(1) # 第1个图形
plt.subplot(211) # 第一个图形的第1个绘图区域
plt.plot([1, 2, 3])
plt.subplot(212) # 第一个图形的第2个绘图区域
plt.plot([4, 5, 6])

plt.figure(2) # 第2个图形
plt.plot([4, 5, 6]) # 创建一个默认的绘图区域

plt.figure(1) # 当前的图形是第1个;当前的绘图区域是(212)
plt.subplot(211) # 设置当前的绘图区域为(211)
plt.title('Easy as 1, 2, 3') # 绘图区域为(211)设置标题

你可以用clf清除当前图形,用cla清除当前的绘画区域。如果您发现后台维护的状态(特别是当前的图像、图形和轴)很烦人,请不要绝望:这只是用来替代使用的,一个围绕面向对象APl的有状态包装器。(参阅Arist教程)。

如果您正在绘制大量的图形(figures),您还需要注意一件事:在图形显式关闭之前,图形所需的内存不会被完全释放。删除对图形的所有引用,或者使用窗口管理器来关闭屏幕上显示图形的窗口,是不可行的,因为pyplot在调用close之前保持内存的引用。

处理文本

text可用于在任意位置添加文本。xlabel、ylabel和title用于在指定位置添加文本(更详细的示例请参见Text in Matplotlib Plots)。

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
# 数据的直方图
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()

在这里插入图片描述

All of the functions return a matplotlib.text.Text instance.Just as with lines above, you cancustomize the properties by passing keyword arguments into the text functions or using setp:

所有的 text函数都返回一个matplotlib.text.Text实例。就像上面的代码一样,您可以通过将关键字参数传递到文 text函数或使用setp来取消属性:

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

这些属性在“Text properties and layout(文本属性和布局)”中有更详细的介绍。

在文本中使用数学表达式

Matplotlib在任何文本表达式中都接受Tex方程表达式。例如,要在标题中写入𝜎𝑖 = 15,您可以编写一个Tex表达式,用美元符号包围:

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

标题字符串前面的r很重要——它表示字符串是一个原始字符串,而不是在python转义时处理反斜杠。Matplotlib有内置的TeX表达式解析器和布局引擎,并拥有自己的数学字体。有关详细信息,请参阅Writing mathematical expressions(数学表达式)。因此,您可以使用跨平台的数学文本,而不需要安装TeX。对于安装了LaTeX和dvipng的用户,还可以使用LaTeX来格式化文本,并将输出直接合并到显示图形或保存到脚本中——请参见Text rendering With LaTeX。

注释文本

使用上面的基本text函数将文本放置在绘图区域的任意位置。文本的一种常见用法是注释图中的某些特性,annotate(注释方法)提供了帮助器功能,使注释变得简单。在注释中,有两点需要考虑:由参数XY表示的位置和文本xytext的位置,这两个参数都是(xy)元组。

ax = plt.subplot()

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位置(文本位置)都在数据坐标中,还有许多其他的坐标系统。参见Basic annotation(基本注释)和Advanced Annotations(高级注释)来获取详细信息。更多的例子可以在/gallery/text_labels_and_annotations/annotation_demo中找到。

对数和其他非线性轴

matplotlib.pyplot supports not only linear axis scales, but also logarithmic and logit scales. This iscommonly used if data spans many orders of magnitude.Changing the scale of an axis is easy:

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

plt.xscale('log')

下面给出了具有相同数据和y轴不同尺度的四幅图的例子。

# 如果使用相同的seed()值,则每次生成的随机数都相同
np.random.seed(19680801)
# 在开放区间(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))
# 使用各种轴比例绘制
plt.figure()
# 线性的
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)
# 对数
plt.subplot(222)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)
# 对称对数
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthresh=0.01)
plt.title('symlog')
plt.grid(True)
# 分对数
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
# than usual, due to y-tick labels like "1 - 10^{-3}"
# 调整subplot子图布局,因为逻辑刻度可能占用更多空间
# 由于y轴标签如:“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()

在这里插入图片描述

你也可以添加自定义的刻度,更多细节请参阅Developer’s guide for creating scales and transformations(开发人员的指南:刻度的创建和转换)。
脚本的总运行时间:(0分3.431秒)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值