前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Matplotlib Pyplot教程

Matplotlib Pyplot教程

作者头像
曲奇
发布2021-12-14 19:01:26
7210
发布2021-12-14 19:01:26
举报
文章被收录于专栏:曲奇的博客

最近自己经常遇到matplotlib的OO API和pyplot包混乱不分的情况,所以抽时间好好把matplotlib的文档读了一下,下面是大概的翻译和总结。很多基础的东西还是要系统地掌握牢固哇~~另外一篇翻译是

matplotlib.pyplot是一个函数的集合,每一个pyplot下面的函数都在figure上做一些动作。

pyplot的动作默认是在当前的Axes上。

代码语言:javascript
复制
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()

如果plot的参数是一个单独的list或array,matplotlib认为它是y值,自动生成x轴从0开始。等价于plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

制定plot的颜色和线型

对于每一个x-y对,都有一个可选的参数,“颜色+线型”的字符串

代码语言:javascript
复制
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro')
plt.axis([0, 6, 0, 20])
plt.show()

根据这个文档可以查看完整的线型和format: plot

axis函数则可以输入[xmin, xmax, ymin, ymax],和其他控制axis的函数。

plot函数可以同时传入多条线和参数

代码语言:javascript
复制
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()

根据keyword参数plot

可以传入字典或pd.DataFrame,np.recarray。matplotlib允许一个data参数。

然后用keyword指定x和y是哪些。

代码语言:javascript
复制
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()

categorical variables

x轴可以是类别型参数

代码语言:javascript
复制
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()

控制线的性质

有三种方法去控制线的性质:

  1. 使用keyword plt.plot(x, y, linewidth=2.0)
  2. 使用Line2D实例的setter方法,plot函数会返回一个Line2D对象。比如line1, line2 = plot(x1, y1, x2, y2) line, = plt.plot(x, y, '-') line.set_antialiased(False) # turn off antialiasing
  3. 使用step函数,它可以为一组对象或单个对象设置参数。参数的格式可以是keyword arguments或string-value对 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) 这是Line2D的参数列表

也可以通过调用step函数,传入line或lines来获取可以设置的属性

代码语言:javascript
复制
In [69]: lines = plt.plot([1, 2, 3])

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

多figures和多Axes

pyplot是在当前figure和当前axes上工作的,通过gca可以拿到当前axes(是一个 matplotlib.axes.Axes实例),通过gcf 可以拿到当前figure实例(matplotlib.figure.Figure实例)。

以下是一个创建两个subplot的实例。这里的figure函数可以不用调用的,默认会创建figure(1)。

代码语言:javascript
复制
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()

如果不显式调用subplot,默认是创建一个subplot(111),如果不手动指定任何axes。subplot指定numrows,numcols,plotnumber。subplot(211)等价于subplot(2,1,1)

能够手动地任意摆放axes,给axes函数传入位置[left, bottom, width, height]

代码语言:javascript
复制
# Creating a new full window axes
plt.axes()

# Creating a new axes with specified dimensions and some kwargs
plt.axes((left, bottom, width, height), facecolor='w')

可以创建多个figure,只要在figure()函数中传入一个递增的数字即可。

代码语言:javascript
复制
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()函数清除当前figure或通过cla()函数清除当前axes。当图片被显式地关闭时(在python shell模式下),内存空间才会释放。调用了show()之后,如果关闭了图片,原先的figure和axes即释放。

图片上所有文本text信息

代码语言:javascript
复制
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 实例,这个实例能够用于step的参数,并对实例设置属性。

数学函数

代码语言:javascript
复制
plt.title(r'$\sigma_i=15$')

注解Annotating

需要指定被注解的位置xy(也就是箭头指向的位置)和文本位置xytext

代码语言:javascript
复制
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()

对数和其他非线性轴

改变一个轴的scale

代码语言:javascript
复制
plt.xscale('log')

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

参考

https://matplotlib.org/tutorials/introductory/pyplot.html#sphx-glr-tutorials-introductory-pyplot-py

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 制定plot的颜色和线型
  • 根据keyword参数plot
  • categorical variables
  • 控制线的性质
  • 多figures和多Axes
  • 图片上所有文本text信息
    • 数学函数
      • 注解Annotating
      • 对数和其他非线性轴
      • 参考
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档