【问题标题】:Printing a Continuous Curve - MatplotLib打印连续曲线 - MatplotLib
【发布时间】:2018-05-21 01:29:45
【问题描述】:

我正在尝试在 Python 中实现神经网络,并且我想绘制每次迭代的成本。

这是我当前的代码的样子 -

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(1, 1, 1)

for i in range(50000):

    if (i % 500 == 0):
        y = np.random.random()  # Cost Function.
        ax.scatter(i, y, label ='Cost')

plt.show()


这是输出 -

问题

该图没有显示一条连续曲线。相反,它以不同的颜色显示不同的点,描绘每次迭代时的 (i, y) 元组。

另外,“标签”在图例上打印了 100 次,这显然不是我想要的。

我正在尝试打印一条连续曲线和一个图例。

我试过ax.plot()而不是ax.scatter(),但它不起作用。

有人可以帮忙吗?我是 Python 新手,我确信我错过了一些基本的东西。我已经尝试在谷歌中搜索答案,但我没有得到任何确定的答案。

谢谢!

【问题讨论】:

  • 使用这个:fig = plt.figure(figsize=(10, 8)) ax = fig.add_subplot(1, 1, 1) x = [] y = [] for i in range(50000): if (i % 500 == 0): y.append(np.random.random()) x.append(i) ax.plot(x, y, '-', label ='Cost') plt.show()

标签: python python-2.7 matplotlib plot


【解决方案1】:

使用scatter 将始终绘制点。 plot 函数具有大量参数选择(包括绘制点的能力),默认为在点对之间绘制线段。在for 循环中的每个步骤中为plot 提供一个点x, y,例如:

for x,y in zip(range(10), range(10)):
    plt.plot(x, y)

不会显示任何东西。这是因为 matplotlib 试图在 xy 的每个输入值之间画一条线。由于每一步只传递一个值,因此它从(x,y)(None, None) 绘制一条线,导致根本没有线。

要绘制一条连续线,您需要将所有坐标对收集到一个可迭代对象(列表、数组等)中,并将它们传递给plot

x = []
y = []
for i in range(50000):
    if (i % 500 == 0):
        x.append(i)
        y.append(np.random.random())  # Cost Function.
ax.plot(x, y, label ='Cost')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-25
    • 1970-01-01
    • 2015-12-15
    • 1970-01-01
    相关资源
    最近更新 更多