简体   繁体   English

Python:使用 matplotlib.pyplot 的奇怪 x 轴限制

[英]Python: Strange x axis limits using matplotlib.pyplot

(Python newbie here) As a learning exercise I am trying to solve and plot the solution to a very simple ODE: dy/dt = y with y(0) = 1. I believe my code to solve the ODE is correct, but the x-axis limits of the plot are very strange. (这里是 Python 新手)作为一个学习练习,我正在尝试解决 plot 解决一个非常简单的 ODE:dy/dt = y with y(0) = 1。我相信我解决 ODE 的代码是正确的,但是plot 的 x 轴限制非常奇怪。 I made 50 equally spaced x-values ranging from 0 to 5, but it looks as if plt.plot() is plotting only the first two points, resulting in the graph looking like a line rather than the curve y = e^x.我制作了 50 个等距的 x 值,范围从 0 到 5,但看起来plt.plot()只绘制前两个点,导致图形看起来像一条线而不是曲线 y = e^x。 I tried playing around with the 'scalex' and 'scaley' arguments of plt.plot() , and I also tried plt.xlim = (0,5) , and variations thereof, but to no avail.我尝试使用plt.plot()的 'scalex' 和 'scaley' arguments ,我还尝试plt.xlim = (0,5)及其变体,但无济于事。 My code is below (I'm using Python 3.7.6):我的代码如下(我使用的是 Python 3.7.6):

import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt

def f(t,y):
    return(y)

t0 = np.linspace(0,5,50)
y0 = np.array([1])

#solve_ivp(fun, t_span, y0, args = None)
out = solve_ivp(f, t0, y0)

t_vals = out.t
y_vals = out.y[0,:]

plt.plot(t_vals,y_vals)


Here's the plot I'm getting:这是我得到的 plot:

I did try setting y = np.exp(t0) and then plotting t0 vs y0, which works perfectly (ie with the x values ranging from 0 to 5).我确实尝试设置y = np.exp(t0) ,然后绘制 t0 与 y0,这非常有效(即 x 值从 0 到 5)。 So I'm not sure why my original code is not giving me the same type of graph.所以我不确定为什么我的原始代码没有给我相同类型的图表。 Perhaps my attempt to subset the variable out is somehow incorrect?也许我尝试将变量子集out在某种程度上是不正确的? ...Any help would be appreciated! ...任何帮助,将不胜感激!

By looking at the documentation for solve_ivp , you can see that t_span should be a 2-tuple of floats, and you can specify the step with max_step通过查看solve_ivp 的文档,您可以看到t_span应该是浮点数的 2 元组,您可以使用max_step指定步骤

So you can have:所以你可以拥有:

from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt

def f(t,y):
    return(y)

out = solve_ivp(f, (0, 5), [1], max_step=0.1)

t_vals = out.t
y_vals = out.y[0,:]

plt.plot(t_vals,y_vals)

Which gives you the expected graph:这为您提供了预期的图表: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM