matplotlib绘图代码示例
时间: 2023-08-20 15:14:32 浏览: 140
以下是三个关于Matplotlib绘图的代码示例:
示例1:绘制线形图
```python
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-2, 2, 100)
y = x**2
z = np.sqrt(4-x**2)
plt.plot(x, y, label='$y=x^2$', color='red', linewidth=2)
plt.plot(x, z, 'b--', label='$x^2 + y^2 = 4$')
plt.plot(x, -z, 'y--', label='$x^2 + y^2 = 4$')
plt.xlabel('x轴')
plt.ylabel('y轴')
plt.title('线形图')
plt.xlim(-5, 5)
plt.ylim(-5, 5)
plt.legend()
plt.grid()
plt.savefig('pyplot.png', format='png', dpi=500)
plt.show()
```
示例2:绘制带箭头的坐标轴
```python
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as axisartist
import numpy as np
fig = plt.figure(figsize=(6, 6))
ax = axisartist.Subplot(fig, 111)
fig.add_axes(ax)
ax.axis[:].set_visible(False)
ax.axis['x'] = ax.new_floating_axis(0, 0)
ax.axis['y'] = ax.new_floating_axis(1, 0)
ax.axis['x'].set_axisline_style('-|>', size=1.0)
ax.axis['y'].set_axisline_style('-|>', size=1.0)
ax.axis['x'].set_axis_direction('top')
ax.axis['y'].set_axis_direction('right')
plt.xlim(-10, 10)
plt.ylim(-0.1, 1.2)
x = np.arange(-10, 10, 0.1)
y = 1/(1 + np.exp(-x))
plt.plot(x, y, label=r'$sigmoid=\frac{1}{1+e^{-x}}$', c='r')
plt.legend()
plt.savefig('sigmoid.png', format='png', dpi=500)
plt.show()
```
示例3:添加图例说明
```python
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 25, 30], label='Philadelphia')
ax.plot([1, 2, 3, 4], [30, 23, 13, 4], label='Boston')
ax.scatter([1, 2, 3, 4], [20, 10, 30, 15], label='Point')
ax.set(ylabel='Temperature (deg C)', xlabel='Time', title='A tale of two cities')
ax.legend()
plt.show()
```
这些示例展示了Matplotlib绘图的不同用法,包括绘制线形图、带箭头的坐标轴和添加图例说明。你可以根据需要选择适合的示例进行使用。
阅读全文