python代码,使用matplotlib简易画出y=2cosx+3sinx图像?(8分)
时间: 2023-05-29 20:04:07 浏览: 234
```python
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 200)
y = 2*np.cos(x) + 3*np.sin(x)
plt.plot(x, y)
plt.show()
```
相关问题
python代码,使用matplotlib简易画出y=2cosx+3sinx图像,带上坐标轴的箭头以及对y的红色表示?(8分)
```python
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 100)
y = 2*np.cos(x) + 3*np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y, color='blue')
ax.arrow(0, 0, 2, 0, length_includes_head=True, head_width=0.1, head_length=0.2, color='black')
ax.arrow(0, 0, 0, 4, length_includes_head=True, head_width=0.1, head_length=0.2, color='black')
ax.text(1.8, 0.2, 'x', fontsize=12)
ax.text(0.2, 3.8, 'y', fontsize=12)
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(12)
label.set_bbox(dict(facecolor='white', edgecolor='none', alpha=0.7))
ax.set_xlim(-0.2, 2*np.pi+0.2)
ax.set_ylim(-5, 5)
ax.fill_between(x, y, where=(y>=0), interpolate=True, color='red')
ax.fill_between(x, y, where=(y<=0), interpolate=True, color='blue')
plt.show()
```
运行结果:
![image.png](attachment:image.png)
在python中画y=sinx,y=cosx,y=tanx,y=cotx四个函数的图像,排成两行两列
在Python中,我们可以使用matplotlib库来绘制y=sin(x), y=cos(x), y=tan(x)以及y=cot(x)这四个三角函数的图像,并通过调整图形的位置排列它们形成两行两列的形式。以下是简单的步骤:
```python
import numpy as np
import matplotlib.pyplot as plt
# 定义x轴范围
x = np.linspace(0, 2 * np.pi, 400)
# 函数列表
functions = [np.sin, np.cos, np.tan, np.arctan] # 注意arctan是cot(x)的逆运算
fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(8, 6))
for i, ax in enumerate(axs.flat):
func_name = "y=" + functions[i].__name__
# 绘制函数曲线
ax.plot(x, functions[i](x))
ax.set_title(func_name)
# 根据行数和列数对齐网格线
if i % 2 == 1:
ax.yaxis.tick_right()
ax.yaxis.grid(True, which='right')
else:
ax.yaxis.grid(True)
# 对偶行之间留空
if i // 2 != axs.shape[0] - 1:
ax.xaxis.set_visible(False)
# 对角线之间设置共同的x轴标签
if i % 2 == 0 and i // 2 == 0:
ax.set_xlabel('X')
plt.tight_layout() # 自动调整间距
plt.show()
阅读全文