[英]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.