使用matplotlib.pyplot进行绘图

1. 导入库

import matplotlib.pyplot as plt
import numpy as np

2. 基础线图

绘制简单的线图并添加轴标签、标题和图例。

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.plot(x, y, label='sin(x)')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.title('Sine Wave')
plt.legend()
plt.show()

3. 多个子图

你可以在同一图形窗口中绘制多个子图。

plt.subplot(2, 1, 1)
plt.plot(x, y)
plt.title('Sine Wave')

plt.subplot(2, 1, 2)
plt.plot(x, np.cos(x))
plt.title('Cosine Wave')

plt.tight_layout()
plt.show()

4. 散点图

plt.scatter(x, y, c='red', marker='o')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.title('Scatter Plot')
plt.show()

5. 直方图

data = np.random.randn(1000)
plt.hist(data, bins=20)
plt.title('Histogram')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.show()

6. 3D图

from mpl_toolkits.mplot3d import Axes3D

x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z = np.sin(np.sqrt(x**2 + y**2))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x, y, z, cmap='viridis')
plt.title('3D Surface Plot')
plt.show()

7. 自定义图例、注释和样式

plt.plot(x, y, label='sin(x)', color='red', linestyle='dashed', linewidth=2)
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.title('Custom Style')
plt.legend(loc='upper right')
plt.annotate('Peak', xy=(1.57, 1), xytext=(2, 1), arrowprops=dict(facecolor='black'))
plt.grid(True)
plt.show()

在这里插入图片描述

8. 保存图形

要将图形保存为文件,你可以使用plt.savefig

plt.plot(x, y)
plt.title('Save This Plot')
plt.savefig('plot.png')

在这里插入图片描述

结论

Matplotlib提供了许多功能和自定义选项,以便你可以准确地创建所需的图形。其语法灵活且强大,允许从简单的线图到复杂的3D可视化。Matplotlib的官方文档和在线社区支持非常丰富,可以帮助你深入了解所有可用的功能和选项。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值