如何在 Python 中使用 matplotlib 创建子图 [英] How to create subplot using matplotlib in Python

查看:59
本文介绍了如何在 Python 中使用 matplotlib 创建子图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了这段代码,但子图中出现错误.我现在不知道我的代码有什么问题.你能帮我吗?

I write this code and I have error in my subplot. I don't now what is wrong in my code. Can you help me ?

import pywt
import scipy.io.wavfile as wavfile

import matplotlib.pyplot as plt

rate,signal = wavfile.read('a0025.wav')
time = [x /rate for x in range(0,len(signal))]
tree = pywt.wavedec(data=signal[:1000], wavelet='db2', level=4, mode='symmetric')
print(len(tree))
newTree = [tree[0]*0, tree[1]*0, tree[2]*0, tree[3]*0, tree[4]]
recSignal = pywt.waverec(newTree,'db2')
fig, ax = plt.subplot(2, 1)
ax[0].plot(time[:1000], signal[:1000])
ax[0].set_xlabel('Czas [s]')
ax[0].set_ylabel('Amplituda')
ax[1].plot(time[:1000], recSignal[:1000])
ax[1].set_xlabel('Czas [s]')
ax[1].set_ylabel('Amplituda')
plt.show()

错误:

 raise ValueError('Illegal argument(s) to subplot: %s' % (args,))
    ValueError: Illegal argument(s) to subplot: (2, 1)

推荐答案

正如错误明确指出的那样,您向 pyplot.subplot() 传递了一个非法参数.如果您查看该功能的文档,您会看到它需要 3 个参数(可以浓缩为一个):ax = plt.subplot(2, 1, 1)ax = plt.subplot(211).

As the error clearly states, you passed an illegal argument to pyplot.subplot(). If you look at the documentation for that function, you'll see that it takes 3 arguments (which can be condensed in one): ax = plt.subplot(2, 1, 1) or ax = plt.subplot(211).

但是,您要查找的功能是 plt.subplots()(请注意最后的 s ),

However, the function that you are looking for is plt.subplots() (note the s at the end), which generates both a figure and an array of subplots:

f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)

这篇关于如何在 Python 中使用 matplotlib 创建子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆