首页 > 解决方案 > 使用 matplotlib 的空白图

问题描述

我正在用 Python 做一门课程(我不希望他们解决课程问题或类似问题),在这一部分中,该课程为您提供了一个代码,以便您可以通过图形可视化机器人的数量(x 轴)和时间步长(y 轴),但是当我运行代码时,它并没有绘制任何图形。我应该怎么办?

对不起,如果这是一个愚蠢的问题,但我对 python 可视化不太擅长。

这是一些代码:

def showPlot1(title, x_label, y_label):
    """
    What information does the plot produced by this function tell you?
    """
    num_robot_range = range(1, 11)
    times1 = []
    times2 = []
    for num_robots in num_robot_range:
        print("Plotting", num_robots, "robots...")
        times1.append(runSimulation(num_robots, 1.0, 20, 20, 0.8, 20, StandardRobot))
        times2.append(runSimulation(num_robots, 1.0, 20, 20, 0.8, 20, RandomWalkRobot))
    pylab.plot(num_robot_range, times1)
    pylab.plot(num_robot_range, times2)
    pylab.title(title)
    pylab.legend(('StandardRobot', 'RandomWalkRobot'))
    pylab.xlabel(x_label)
    pylab.ylabel(y_label)
    pylab.show()

showPlot1("Title", "Number of robots", "Time-steps")

这是它显示的内容:

空白处绘图

这是它打印的内容:

Plotting 1 robots...
801.95
2019.15
Plotting 2 robots...
387.35
997.35
Plotting 3 robots...
256.4
732.7
Plotting 4 robots...
201.3
430.2
Plotting 5 robots...
158.25
366.3
Plotting 6 robots...
133.15
328.0
Plotting 7 robots...
113.65
276.1
Plotting 8 robots...
100.0
239.9
Plotting 9 robots...
85.9
191.85
Plotting 10 robots...
78.1
162.3

谢谢你的帮助!

标签: pythonmatplotlibvisualization

解决方案


我写了一个假人runSimulation

def runSimulation(nrobots, a,b,c,d,e, randomrobot):
    if randomrobot:
        result = (450+100*rand())/(nrobots*(1+0.05-rand()*0.10))
    else:
        result = (900+200*rand())/(nrobots*(1+0.05-rand()*0.10))
    print("%10.3f"%result, end='')
    return result

而且,完全使用showPlot1您发布的内容,我得到了一个完美的情节

在此处输入图像描述

然后我return result从我的虚拟代码中删除了该语句,这就是我得到的(注意轴的限制,与您的图中相同)

在此处输入图像描述

我的结论是,你return something的版本没有结果runSimulation——请检查你的代码,如果我的猜测是正确的,请告诉我们。


推荐阅读