【问题标题】:Plotting several runs of the same function on one plot using Matplotlib使用 Matplotlib 在一个绘图上绘制同一函数的多次运行
【发布时间】:2022-01-19 22:24:35
【问题描述】:

我有一个函数可以给我 3 个输出 T、A 和 B

我试图在同一个图上绘制该函数的多次运行。每次运行我都会得到一个新的情节。我已经把代码放在下面请看看你是否知道修复:)

# create the different runs
setT=[]
setA=[]
setB=[]
for i in range(5):
    smallNT,smallNA,smallNB = ABA(50,40,3,2)
    setT.append(smallNT)
    setA.append(smallNA)
    setB.append(smallNB)

#plot the runs
def plotr(feat1,feat2,feat3):
    time1=[]
    size1=[]
    size2=[]
    for i in range(0,100):
        time1.append(feat1[i])
        size1.append(feat2[i])
        size2.append(feat3[i])

    plt.plot(time1,size1, 'ro')
    plt.plot(time1,size2, 'bo')
    plt.xlabel("Time")
    plt.ylabel("size of population")
    plt.show()

#trying to plot them all together
for i in range(5):
    plotr(setT[i],setA[i],setB[i])

【问题讨论】:

  • 每次调用 plotr() 时,您都会使用 plt.show() 显示绘图。将 xlabel、ylabel 和 show() 移动到代码的末尾。

标签: python python-3.x matplotlib


【解决方案1】:

假设我随机生成这些数据集setTsetAsetB。每个都是一个 5x20 数组(5 次运行,每次运行有 20 个数据点)。

我建议您在循环外使用plt.subplots 创建一个Axis。它将返回FigureAxis。然后你将Axis 变量传递给函数,这样我们就可以多次重用它。

import numpy as np
import matplotlib.pyplot as plt

setT = np.random.rand(5, 20)
setA = np.random.rand(5, 20)
setB = np.random.rand(5, 20)

def plotr(ax, feat1,feat2,feat3):
    ax.plot(feat1, feat2, 'ro')
    ax.plot(feat1, feat3, 'bo')
    ax.set_xlabel("Time")
    ax.set_ylabel("size of population")

fig, ax = plt.subplots()
for i in range(5):
    plotr(ax, setT[i],setA[i],setB[i])
plt.show()

如果您只想绘制第一个 N 数据点,则无需像您所做的那样使用另一个 for 循环创建新列表并将它们分配给列表。您可以只使用列表切片,如 feat1[:N]feat[:100]。因此,在plotr 函数中,您将这两行更改为:

    ax.plot(feat1[:100], feat2[:100], 'ro')
    ax.plot(feat1[:100], feat3[:100], 'bo')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 2020-06-19
    • 2017-02-24
    • 2019-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多