matplotlib基础知识
时间: 2023-12-20 16:32:44 浏览: 74
matlib 基本知识
5星 · 资源好评率100%
以下是关于matplotlib基础知识的介绍和演示:
1. 绘制静态图像:
```python
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Sine Curve')
plt.show()
```
2. 绘制动态图像:
```python
import matplotlib.pyplot as plt
from matplotlib import animation
import numpy as np
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))
def animate(i):
line.set_ydata(np.sin(x + i/10.0))
return line,
def init():
line.set_ydata(np.sin(x))
return line,
ani = animation.FuncAnimation(fig, animate, frames=100, init_func=init, interval=20, blit=True)
plt.show()
```
3. 添加图例:
```python
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
y1 = np.sin(x)
y2 = np.square(x)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--', label='Sine Curve')
plt.plot(x, y2, label='Square Curve')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Sine and Square Curves')
plt.legend()
plt.show()
```
阅读全文