【问题标题】:I am getting two plots for one data set in python我在 python 中为一个数据集得到两个图
【发布时间】:2017-04-02 19:28:47
【问题描述】:

我正在研究 Mark Newman 的《计算物理学》一书中标题为 Euler's Method 的示例 8.1。我将示例重写为使用 Numpy 数组的方法,但是当我绘制它时,我在同一个图中得到了两个图,不知道如何更正它。还有更好的方法将我的 2 个 1D 数组转换为 1 个 2D 数组以用于在 Matplotlib 中绘图,谢谢。

纽曼的例子:

from math import sin
from numpy import arange
from pylab import plot,xlabel,ylabel,show

def f(x,t):
    return -x**3 + sin(t)

a = 0.0           # Start of the interval
b = 10.0          # End of the interval
N = 1000          # Number of steps
h = (b-a)/N       # Size of a single step
x = 0.0           # Initial condition

tpoints = arange(a,b,h)
xpoints = []
for t in tpoints:
    xpoints.append(x)
    x += h*f(x,t)

plot(tpoints,xpoints)
xlabel("t")
ylabel("x(t)")
show()

我的修改:

from pylab import plot,show,xlabel,ylabel
from numpy import linspace,exp,sin,zeros,vstack,column_stack


def f(x,t):
    return (-x**(3) + sin(t))

def Euler(f,x0,a,b):
    N=1000    
    h = (b-a)/N
    t = linspace(a,b,N)
    x = zeros(N,float)
    y = x0
    for i in range(N):
        x[i] = y
        y += h*f(x[i],t[i])

    return column_stack((t,x)) #vstack((t,x)).T


plot(Euler(f,0.0,0.0,10.0))
xlabel("t")
ylabel("x(t)")
show()

【问题讨论】:

  • 我想您的第一个问题是您需要以某种方式清除绘图空间。我不太了解 Pyplot,但在 Matplotlib 中有一个 plt.clf()
  • @Henry 刚刚尝试过,虽然它有帮助,但由于某种原因,主线性图仍然显示出来,它似乎需要一个数据集并从中绘制两张图。
  • 对不起,兄弟。没有使用 pyplot 的经验!
  • @Henry 很好的清理确实帮助我解决了另一个问题
  • @Henry pyplot plt 如果你是imported matplotlib.pyplot as pltpylab 也只是 pyplot 的不同命名空间。

标签: python arrays numpy matplotlib


【解决方案1】:

你得到两行的原因是tx 是针对它们的索引绘制的,而不是x 针对t 绘制的

我不明白你为什么要堆叠这两个数组。只是保持then分开,这也将解决两个情节的问题。

以下工作正常。

import numpy as np
import matplotlib.pyplot as plt
f = lambda x,t: -x**3 + np.sin(t)

def Euler(f,x0,a,b):
    N=1000    
    h = (b-a)/N
    t = np.linspace(a,b,N)
    x = np.zeros(N,float)
    y = x0
    for i in range(N):
        x[i] = y
        y += h*f(x[i],t[i])

    return t,x

t,x = Euler(f,0.0,0.0,10.0)
plt.plot(t,x)
plt.xlabel("t")
plt.ylabel("x(t)")
plt.show()

【讨论】:

    猜你喜欢
    • 2019-03-31
    • 1970-01-01
    • 2020-03-15
    • 2016-02-20
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多