matplotlib.pyplot可视化(官方API)

线
import matplotlib.pyplot as plt
x = [1,2,3,4,5,6]
y = [3,4,6,7,3,2]
plt.xlabel('x')
plt.ylabel('y')
plt.plot(x,y)

在这里插入图片描述

官方示例:

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

格式化绘图样式
对于每对x,y参数,都有一个可选的第三个参数,它是指示绘图颜色和线型的格式字符串。 格式字符串的字母和符号来自MATLAB,您可以将颜色字符串与线条样式字符串连接起来。 默认格式字符串是‘b-’,它是一条蓝色实线。 例如,要用红色圆圈绘制上面的内容,可以执行以下命令:

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

在这里插入图片描述
plt.plot()详细用法参见:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot.
plt.axis()详细用法参见:
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.axis.html#matplotlib.pyplot.axis.

使用数组在一个函数调用中绘制具有不同格式样式的几行:

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

在这里插入图片描述
plt.subplot()详细用法参见:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplot.html#matplotlib.pyplot.subplot.
plt.bar()详细用法参见:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.bar.html#matplotlib.pyplot.bar.
plt.scatter()详细用法参见:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.scatter.html#matplotlib.pyplot.scatter.

控制线属性

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

使用关键字args:

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

使用Line2D实例的setter方法。 plot返回Line2D对象的列表; 例如,第1行,第2行= plot(x1,y1,x2,y2)。 在下面的代码中,我们假设只有一行,因此返回的列表的长度为1。我们使用tuple与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)

要获取可设置行属性的列表,请使用一行或多行作为参数调用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(1),就像如果不手动指定任何轴,默认情况下将创建子图(111)。 子图调用指定编号,编号,点数,其中绘图号的范围是1到编号*编号。 如果numrows * numcols <10,则子图调用中的逗号是可选的。 因此subplot(211)与subplot(2,1,1)相同。

您可以创建任意数量的子图和轴。 如果要手动放置轴(即不在矩形网格上),请使用轴,该轴可让您将位置指定为轴([左,下,宽度,高度]),其中所有值均为小数(0至1) )坐标。 有关手动放置轴的示例,请参见“轴演示”;有关具有大量子图的示例,请参见“基本子图”演示。

您可以通过使用多个具有递增数字的图形调用来创建多个图形。 当然,每个图形都可以包含您的心脏所需的多个轴和子图:

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清除当前轴。 如果您发现在后台为您维护状态(特别是当前图像,图形和轴)很烦人,请不要绝望:这只是面向对象API的薄状态包装,您可以使用它( 参见艺术家教程)

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

处理文字

text可用于在任意位置添加文本,xlabel,ylabel和title可用于在指定位置添加文本(有关更多详细示例,请参见Matplotlib图中的Text:

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

在这里插入图片描述
所有文本函数都返回一个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很重要-它表示该字符串是原始字符串,并且不将反斜杠视为python转义。 matplotlib具有内置的TeX表达式解析器和布局引擎,并附带了自己的数学字体-有关详细信息,请参见链接: https://matplotlib.org/tutorials/text/mathtext.html。 因此,您可以跨平台使用数学文本,而无需安装TeX。 对于安装了LaTeX和dvipng的用户,您还可以使用LaTeX设置文本格式并将输出直接合并到显示图形或保存的后记中-请参阅。https://matplotlib.org/tutorials/introductory/customizing.html.

注释文本

上面的基本文本功能的使用将文本放置在轴上的任意位置。 文本的常用用法是对绘图的某些功能进行注释,并且annotate方法提供了帮助程序功能以简化注释。 在注释中,有两点要考虑:由参数xy表示的要注释的位置和文本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()

在这里插入图片描述
对数轴和其他非线性轴

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

plt.xscale(‘log’)

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

# 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', linthresh=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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值