Matplotlib 坐标轴箭头:快速添加箭头以增强可视化
使用 Matplotlib 的 annotate 函数可以在坐标轴两端添加箭头,使图表更清晰易懂。以下是如何实现:
- 导入 Matplotlib 库
import matplotlib.pyplot as plt
- 创建图形对象和子图对象
fig, ax = plt.subplots()
- 绘制图形
# 绘制函数曲线或散点图等
- 给 x 轴和 y 轴添加箭头
# 给 x 轴添加箭头
ax.annotate('', xy=(max_x, 0), xytext=(min_x, 0), arrowprops=dict(arrowstyle='->'))
# 给 y 轴添加箭头
ax.annotate('', xy=(0, max_y), xytext=(0, min_y), arrowprops=dict(arrowstyle='->'))
其中,arrowstyle 参数可以设置箭头的样式,例如 '->' 表示带箭头的直线。
完整代码示例:
import matplotlib.pyplot as plt
import numpy as np
# 创建数据
x = np.linspace(-5, 5, 100)
y = np.sin(x)
# 创建图形对象和一个子图对象
fig, ax = plt.subplots()
# 绘制函数曲线
ax.plot(x, y)
# 获取 x 轴和 y 轴的最大值和最小值
min_x, max_x = ax.get_xlim()
min_y, max_y = ax.get_ylim()
# 给 x 轴添加箭头
ax.annotate('', xy=(max_x, 0), xytext=(min_x, 0), arrowprops=dict(arrowstyle='->'))
# 给 y 轴添加箭头
ax.annotate('', xy=(0, max_y), xytext=(0, min_y), arrowprops=dict(arrowstyle='->'))
# 显示图形
plt.show()
原文地址: https://www.cveoy.top/t/topic/m1sk 著作权归作者所有。请勿转载和采集!