gpt4 book ai didi

python - 自动缩放不适用于绘图箭头

转载 作者:太空宇宙 更新时间:2023-11-03 11:46:42 26 4
gpt4 key购买 nike

尝试使用以下方法在 Matplotlib 中绘制一个简单的箭头:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.arrow(1, 1, 1, 1)
plt.show()

这会导致一个空图。

如果箭头规范更改为 ax.arrow(0, 0, 1, 1) 那么我确实会在最终图中看到一个箭头。所以我怀疑这可能是轴缩放的问题,所以我根据 Matplotlib autoscale 中的建议修改了代码。到以下内容:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.arrow(1, 1, 1, 1)
ax.relim()
ax.autoscale_view()
plt.show()

这也行不通。

我发现手动设置限制如下所示

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.arrow(1, 1, 1, 1)
ax.set_xlim(0, 5)
ax.set_ylim(0, 5)
plt.show()

奇怪的是我还发现 ax.set_xlim() 单独或 ax.set_ylim() 单独不起作用我必须将箭头的两个限制设置为变得可见。

问题:

  • ax.arrow 是否需要特殊处理?
  • 除了 ax.relim()ax.autoscale_view() 之外,我是否遗漏了一些命令?
  • 为什么我必须同时设置 xlimylim

版本:

  • python :3.5.1
  • Matplotlib:1.5.1
  • Linux:64 位 Archlinux

最佳答案

问题仍然存在于 Windows 10 和 Ubuntu 14 以及最新版本的 matplotlib 和 Python 3.4/3.5。一个简单的解决方法是创建一个辅助函数 arrow_,它在箭头的开始和结束处创建两个不可见的点。

import matplotlib.pyplot as plt
fig, ax = plt.subplots()

def arrow_(ax, plt, x, y, dx, dy, **kwargs):
ax.arrow(x, y, dx, dy, **kwargs)
plt.plot([x, x + dx + 0.1], [y, y + dx + 0.1], alpha=0)

arrow_(ax, plt, 1, 1, 1, 1)
ax.relim()
#plt.plot([1.8], [1.5], 'ro')
ax.autoscale_view()
plt.show()
  • 注释行只是为了证明不可见的点不会干扰图形的其余部分。
  • 增加0.1的值只是为了补偿箭头。

关于python - 自动缩放不适用于绘图箭头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37899364/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com