根据如下绘图写出相应代码绘图函数:y=sin(x),y=cos(x),x=np.linspace(-np.pi,np.pi,256,endpoint=True)并绘制填充区域:(-2.5<x)&(x<-0.5)紫色区域:np.abs(x)<0.5,sinx>0.5绿色区域:color='purple'
时间: 2024-03-30 20:33:39 浏览: 182
以下是绘制函数的代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 设置x轴的取值范围为-π到π
x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
# 计算sin(x)和cos(x)的值
y_sin = np.sin(x)
y_cos = np.cos(x)
# 绘制sin(x)和cos(x)的曲线
plt.plot(x, y_sin, color='blue', linewidth=1.5, linestyle="-", label="sin(x)")
plt.plot(x, y_cos, color='red', linewidth=1.5, linestyle="-", label="cos(x)")
# 绘制填充区域
plt.fill_between(x, np.sin(x), where=((x > -2.5) & (x < -0.5)), color='purple', alpha=0.5)
plt.fill_between(x, np.sin(x), where=((np.abs(x) < 0.5) & (np.sin(x) > 0.5)), color='green', alpha=0.5)
# 设置图像的标题和轴标签
plt.title("Sin(x) and Cos(x) Curves")
plt.xlabel("x")
plt.ylabel("y")
# 显示图例
plt.legend(loc='upper left')
# 显示图像
plt.show()
```
运行以上代码,即可看到绘制出sin(x)和cos(x)的曲线,并且填充了紫色和绿色的区域。
阅读全文