【问题标题】:fill color between arrowheads in a quiver plot在箭袋图中的箭头之间填充颜色
【发布时间】:2022-01-18 05:44:45
【问题描述】:

我在箭袋图中绘制了几个箭头,我想知道是否有办法用颜色填充箭头之间的形状。 箭袋图如下所示:

import numpy as np
import matplotlib.pyplot as plt

theta = np.linspace( 0 , 2 * np.pi , 40 ) 
R = 5.0
x = R * np.cos( theta ) 
y = R * np.sin( theta ) 
m2_x = 9.0
m2_y = 9.0
u = -(x - m2_x)/((m2_x - x)**2 + (m2_y - y)**2)**2 
v = -(y - m2_y)/((m2_x - x)**2 + (m2_y - y)**2)**2 

fig, ax = plt.subplots(figsize=(7,7))
ax.quiver(x,y,u,v, headwidth=2, headlength=5, width=0.005)
ax.set_xlim((-20,20))
ax.set_ylim((-20,20))

我想用颜色填充箭头所描绘的圆形,或者至少用一条线连接箭头。看起来应该很简单,但我还没有找到。

【问题讨论】:

  • 使用ax.plot(x+3000*u,y+3000*v) 似乎有效,但我不知道为什么比例因子应该是3000。我的直觉是它与您正在使用的xlimylim 有关(更多信息here

标签: python matplotlib


【解决方案1】:

quiver 为箭头返回 specialized PolyCollection。箭头的尖端是每个箭头的顶点#3。从这个集合中,我们得到箭头的坐标并创建一个PathPatch 以添加到轴:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.patches as mpatches

theta = np.linspace( 0 , 2 * np.pi , 40 ) 
R = 5.0
x = R * np.cos( theta ) 
y = R * np.sin( theta ) 
m2_x = 9.0
m2_y = 9.0
u = -(x - m2_x)/((m2_x - x)**2 + (m2_y - y)**2)**2 
v = -(y - m2_y)/((m2_x - x)**2 + (m2_y - y)**2)**2 

fig, ax = plt.subplots(figsize=(7,7))
q = ax.quiver(x,y,u,v, headwidth=2, headlength=5, width=0.005)
ax.set_xlim((-20,20))
ax.set_ylim((-20,20))

# draw the quiver to get the coordinates of the arrows
fig.draw_without_rendering()

# get x,y in display coords (pixels)
xy_disp = q.transform.transform(q.properties()['offsets'])

# get arrow heads in display coords, relative to x,y
heads_rel = np.vstack([p.vertices[3] for p in q.properties()['paths']])
heads_rel_disp = q.properties()['transform'].transform(heads_rel)

# get arrow heads in absolute data coordinates
heads = q.transform.inverted().transform(xy_disp + heads_rel_disp)

# draw patch
ax.add_patch(mpatches.PathPatch(mpath.Path(heads), fc='r', alpha=0.5))

【讨论】:

  • 谢谢!出于某种原因,执行代码时出现错误:```ValueError: need at least one array to concatenate``` for the line heads_rel = np.vstack([p.vertices[3] for p in q.properties()['paths']])
  • 嗯,你使用什么 matplotlib 版本(示例适用于 3.5.0)? q.properties()['paths'] 的输出是什么?
  • 是的,我更新了我的 matplotlib,它现在可以完美运行了!谢谢!!!