[英]Python, matplotlib. Plot a function between two points
我想使用 matplotlib 在 2 个点之间绘制一个函数。 类似的问题,但对于 3d 情况没有工作答案: 如何绘制面向局部 x 轴 matplotlib 3d 的函数?
我认为它应该像这样工作:
import matplotlib.pyplot as plt
import math
def foo(x, L):
# some polynomial on [0, L]
return x**2 # usually it's more difficult
def magic(plt, foo, point1, point2):
"""
Plot foo from point1 to point2
:param plt: matplotlib.pyplot
:param foo: function
:param point1: tuple (x1, y1) or list [x1, y1]
:param point2: tuple (x2, y2) or list [x2, y2]
:return:
"""
# do magic
# create modified function along new local x' axis using points in initial x,y axis?
# create new axis, rotate and move them?
pass
x1, y1 = 1, 1 # first point coordinates
x2, y2 = 2, 2 # second point coordinates
dx = x1 - x2
dy = y1 - y2
# length, this ratio is always True in my case (see picture below)
L = math.sqrt(dx * dx + dy * dy)
ax, fig = plt.subplots()
magic(plt, foo, (x1,y1), (x2, y2))
plt.show()
重要:沿新轴的长度不会改变。 如果[0, L]
上有一个函数[0, L]
则意味着它在旋转/移动或沿新轴表示后将具有相同的域(或“长度”)。
这是我正在尝试做的事情的图像
不涉及魔法。 只是从 (0,0) 到 (x1,y1) 的平移和由 dx 和 dy 定义的角度旋转。 该角度的正弦是 dy/L,余弦是 dx/L。 使用numpy数组既可以方便地编写函数,又可以加快计算速度。
在下面的代码中,我更改了示例函数,以更清楚地说明函数是如何转换的。 此外,纵横比设置为“相等”。 否则旋转后的函数看起来会失真。
import matplotlib.pyplot as plt
import numpy as np
def foo(x):
# some function on [0, L]
return np.sin(x*20)/(x+1)
def function_on_new_axis(foo, point1, point2):
"""
Plot foo from point1 to point2
:param foo: function
:param point1: tuple (x1, y1) or list [x1, y1]
:param point2: tuple (x2, y2) or list [x2, y2]
:return:
"""
# create modified function along new local x' axis using points in initial x,y axis?
# create new axis, rotate and move them?
dx = x2 - x1
dy = y2 - y1
L = np.sqrt(dx * dx + dy * dy)
XI = np.linspace(0, L, 500) # initial coordinate system
YI = foo(XI)
s = dy / L # sine of the rotation angle
c = dx / L # cosine of the rotation angle
XM = c * XI - s * YI + x1 # modified coordinate system
YM = s * XI + c * YI + y1
plt.plot(XI, YI, color='crimson', alpha=0.3)
plt.plot(XM, YM, color='crimson')
plt.plot([x1, x2], [y1, y2], 'go')
x1, y1 = 1, 1 # first point coordinates
x2, y2 = 2, 3 # second point coordinates
fig, ax = plt.subplots()
function_on_new_axis(foo, (x1,y1), (x2, y2))
ax.axis('equal') # equal aspect ratio between x and y axis to prevent that the function would look skewed
# show the axes at (0,0)
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.