matplotlib 函数区间

kr98yfug  于 2023-06-06  发布在  其他
关注(0)|答案(1)|浏览(202)

我有3个函数,我如何使用不同的间隔绘制它们?
这是我的代码:

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5,5,100)
y = 2*x+1
k = 3*x+2
i = 2*x+2
plt.plot(x, y, '-r', label='y=2x+1')
plt.plot(x, k, '-r', label='k =3x+2')
plt.plot(x, i, '-r', label='i =2x+2')
plt.title('3 functions on 3 intervals')
plt.xlabel('x', color='#1C2833')
plt.ylabel('y', color='#1C2833')
plt.legend(loc='upper left')
plt.grid()
plt.show()

想要的样式:3个区间,3个线性函数:

这就是我得到的:

我的愿望是在下面的区间[x:2->x:8]上绘制第一个函数2x+1。
第二个函数3
x+2必须在区间[x:8->x:12]上绘制
第三个函数2*x+2必须在区间[x:12->x:20]上绘制
这可能吗?
编辑:结束了这个:

x = np.linspace(-5,0,100)
t = np.linspace(0,5,100)
m = np.linspace(5,10,100)
y = 2*x+1
k = 3*x-2
i = 2*x+2
plt.plot(x, y, '-r', label='y=2x+1')
plt.plot(t, k, '-r', label='k =3x-2')
plt.plot(m, i, '-r', label='i =2x+2')

结果:

o8x7eapl

o8x7eapl1#

这就是你想要的吗

In [33]: import matplotlib.pyplot as plt
    ...: import numpy as np
    ...: 
    ...: xs = [np.linspace(0,4), np.linspace(-3, 5), np.linspace(4, 10)]
    ...: fs = [np.cos, np.sin, lambda x:np.sin(x)-2*np.cos(x)]
    ...: for x, f in zip(xs, fs):
    ...:     plt.plot(x, f(x), label=f.__name__)
    ...: plt.legend()
    ...: plt.show()

绘制一个线性函数没有什么不同,

import matplotlib.pyplot as plt
import numpy as np

xs = [np.linspace(0,4), np.linspace(-3, 5), np.linspace(4, 10)]
fs = [np.cos, np.sin, lambda x:(x-6)*0.5]
fs[-1].__name__ = 'x/2-3'
for x, f in zip(xs, fs):
    plt.plot(x, f(x), label=f.__name__)
plt.legend()
plt.show()

当且仅当你只绘制线性函数,另一种方法可能是

import matplotlib.pyplot as plt

# plotting y = a x + b
y = lambda xmin, xmax, a, b: (a*xmin+b, a*xmax+b)
format = lambda b: ("y = %.2f x + %.2f"if b>=0 else"y = %.2f x – %.2f")
Xmin = [0, 4, 7]
Xmax = [5, 6, 9]
A = [1, 0.5, 3]
B = [-2, 0, 3]

for xmin, xmax, a, b in zip(Xmin, Xmax, A, B):
    plt.plot((xmin, xmax), y(xmin, xmax, a, b),
             label=format(b)%(a, abs(b)))
plt.legend()
plt.show()

相关问题