在Python中使用matplotlib库画图并添加箭头,可以通过以下几种方法实现:
1. 使用`ax.arrow()`函数:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
箭头起始位置和终点位置
A = [0, 0]
B = [2, 2]
绘制箭头
ax.arrow(A, A, B - A, B - A, length_includes_head=True, head_width=0.5, head_length=0.5, fc='r', ec='r')
绘制图形
ax.plot([3, 3], [3, 3], color='k', alpha=1, marker='o', markersize=1)
设置图形范围
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
添加网格
ax.grid()
设置坐标轴等比例
ax.set_aspect('equal')
plt.show()
2. 使用`ax.annotate()`函数:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
箭头起始位置和终点位置
A = [0, 0]
B = [2, 2]
绘制箭头
ax.annotate("", xy=B, xytext=A, arrowprops=dict(arrow))
绘制图形
ax.plot([3, 3], [3, 3], color='k', alpha=1, marker='o', markersize=1)
设置图形范围
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
添加网格
ax.grid()
设置坐标轴等比例
ax.set_aspect('equal')
plt.show()
3. 使用`mpatches.FancyArrowPatch`:
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
fig, axs = plt.subplots(nrows=2)
箭头起始位置和终点位置
x_tail = 0.1
y_tail = 0.1
x_head = 0.9
y_head = 0.9
dx = x_head - x_tail
dy = y_head - y_tail
创建箭头对象
arrow = mpatches.FancyArrowPatch((x_tail, y_tail), (dx, dy), head_width=0.5, head_length=0.5, fc='r', ec='r')
添加箭头到轴
axs.add_patch(arrow)
绘制图形
axs.plot([3, 3], [3, 3], color='k', alpha=1, marker='o', markersize=1)
设置图形范围
axs.set_xlim(0, 10)
axs.set_ylim(0, 10)
添加网格
axs.grid()
设置坐标轴等比例
axs.set_aspect('equal')
plt.show()
以上代码展示了如何使用`ax.arrow()`、`ax.annotate()`和`mpatches.FancyArrowPatch`函数在matplotlib中添加箭头。你可以根据需要调整箭头的样式和位置。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/138151.html