使用numpy和matplotlib绘制带局部阴影的坐标系,两条曲线分别是y = cos(2Πx)exp(-x)+0.8和 y = 0.5 cos(x2)+0.8,两条曲线间阴影区间自定义
时间: 2024-04-01 15:36:36 浏览: 140
好的,我可以帮你实现这个任务。首先,让我们导入需要的库:
```python
import numpy as np
import matplotlib.pyplot as plt
```
接下来,我们定义两条曲线的函数:
```python
def f1(x):
return np.cos(2*np.pi*x)*np.exp(-x) + 0.8
def f2(x):
return 0.5*np.cos(x**2) + 0.8
```
然后,我们生成x轴的数据:
```python
x = np.linspace(0, 3, 1000)
```
接下来,我们根据自定义的阴影区间,生成两条曲线的y轴数据:
```python
y1 = f1(x)
y2 = f2(x)
shade_x = np.linspace(1, 2, 1000)
shade_y1 = f1(shade_x)
shade_y2 = f2(shade_x)
```
现在,我们可以开始绘制坐标系了。首先,我们绘制两条曲线:
```python
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(x, y1, label='y = cos(2πx)exp(-x)+0.8', linewidth=2)
ax.plot(x, y2, label='y = 0.5 cos(x^2)+0.8', linewidth=2)
```
然后,我们使用fill_between函数绘制阴影:
```python
ax.fill_between(shade_x, shade_y1, shade_y2, where=(shade_y1 > shade_y2), color='gray', alpha=0.2)
ax.fill_between(shade_x, shade_y1, shade_y2, where=(shade_y1 < shade_y2), color='gray', alpha=0.2)
```
最后,我们添加坐标轴标签和图例,并显示图像:
```python
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend()
plt.show()
```
完整代码如下:
```python
import numpy as np
import matplotlib.pyplot as plt
def f1(x):
return np.cos(2*np.pi*x)*np.exp(-x) + 0.8
def f2(x):
return 0.5*np.cos(x**2) + 0.8
x = np.linspace(0, 3, 1000)
y1 = f1(x)
y2 = f2(x)
shade_x = np.linspace(1, 2, 1000)
shade_y1 = f1(shade_x)
shade_y2 = f2(shade_x)
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(x, y1, label='y = cos(2πx)exp(-x)+0.8', linewidth=2)
ax.plot(x, y2, label='y = 0.5 cos(x^2)+0.8', linewidth=2)
ax.fill_between(shade_x, shade_y1, shade_y2, where=(shade_y1 > shade_y2), color='gray', alpha=0.2)
ax.fill_between(shade_x, shade_y1, shade_y2, where=(shade_y1 < shade_y2), color='gray', alpha=0.2)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend()
plt.show()
```
运行代码,你会得到如下图像:
![坐标系.png](https://i.loli.net/2021/06/08/FSW6L7VzjG3ZC4B.png)
这就是一个带局部阴影的坐标系,其中两条曲线分别是y = cos(2Πx)exp(-x)+0.8和 y = 0.5 cos(x2)+0.8,阴影区间为x=1到x=2。
阅读全文