子图设置 请编程,将练习11-2至11-8的所有图绘制在一个画布中,每个图作为一个子图
时间: 2024-03-06 19:48:53 浏览: 51
python 实现在一张图中绘制一个小的子图方法
好的,以下是使用 matplotlib 库绘制子图的代码:
```python
import matplotlib.pyplot as plt
import numpy as np
# 练习 11-2
x = np.arange(0, 10, 0.1)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Exercise 11-2')
# 练习 11-3
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
fig, ax = plt.subplots()
ax.plot(x, y1, label='sin(x)')
ax.plot(x, y2, label='cos(x)')
ax.legend()
ax.set_title('Exercise 11-3')
# 练习 11-4
x = np.arange(0, 10, 0.1)
y = np.exp(x)
fig, ax = plt.subplots()
ax.semilogy(x, y)
ax.set_title('Exercise 11-4')
# 练习 11-5
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.tan(x)
fig, ax = plt.subplots()
ax.plot(x, y1, label='sin(x)')
ax.plot(x, y2, label='tan(x)')
ax.legend()
ax.set_title('Exercise 11-5')
# 练习 11-6
x = np.linspace(-10, 10, 100)
y = np.sqrt(100 - x**2)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.plot(x, -y)
ax.set_title('Exercise 11-6')
# 练习 11-7
x = np.linspace(-10, 10, 100)
y1 = x**2
y2 = np.abs(x)
fig, axs = plt.subplots(1, 2)
axs[0].plot(x, y1)
axs[0].set_title('y=x^2')
axs[1].plot(x, y2)
axs[1].set_title('y=|x|')
# 练习 11-8
x = np.linspace(-10, 10, 100)
y1 = np.sin(x)
y2 = np.exp(-x**2)
fig, axs = plt.subplots(2, 1)
axs[0].plot(x, y1)
axs[0].set_title('y=sin(x)')
axs[1].plot(x, y2)
axs[1].set_title('y=exp(-x^2)')
plt.show()
```
这段代码将练习 11-2 至 11-8 的图像绘制在一个画布中,每个图像作为一个子图显示。你可以根据需要对代码进行修改,比如调整子图的排列方式等。
阅读全文