for循环中有多个“subplot2grid”

2024-10-05 11:01:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着画出两个不同的函数集,一次通过一个双循环。我不知道如何才能让sublot2grid对第二个数字执行操作。在

import numpy as np
from matplotlib import pyplot as plt
t=np.linspace(0,1,100)
fig1=plt.figure()
for i in range(3):
    for j in range(3):
        plt.subplot2grid((3,3),(i,j))
        plt.plot(t,np.sin((t*np.random.random()*10)))
fig2=plt.figure()
for i in range(3):
    for j in range(3):
        plt.subplot2grid((3,3),(i,j))
        plt.plot(t,np.cos((t*np.random.random()*10)))
plt.show()

有没有办法只用一个循环就可以做到这一点?在

enter image description hereenter image description here


Tags: 函数inimportnumpyforplotasnp
1条回答
网友
1楼 · 发布于 2024-10-05 11:01:01

你应该使用面向对象的接口。下面是一个例子:

import numpy as np
from matplotlib import pyplot as plt

t = np.linspace(0, 1, 100)
fig1, axes1 = plt.subplots(3, 3)
fig2, axes2 = plt.subplots(3, 3)

blue, red = "#1E90FF", "#FF6347"
for i in range(3):
    for j in range(3):
        axes1[i, j].plot(t, np.sin((t * np.random.random() * 10)), blue)
        axes2[i, j].plot(t, np.cos((t * np.random.random() * 10)), red)

fig1.tight_layout()
fig2.tight_layout()

enter image description hereenter image description here

相关问题 更多 >

    热门问题