Skip to main content
 首页 » 编程设计

python之以编程方式更改 matplotlib 填充数据

2025年05月04日12duanxz

我正在使用 Matplotlib 创建动画并使用 Fill 对象。我希望能够从一个函数中更改填充数据。对于其他绘图类型,通常有一个 set_data() 函数或 set_offsets()。 Fill 好像没有。我希望做类似下面代码的事情,但这不起作用。有什么想法吗?

import matplotlib.pyplot as plt 
fig = plt.figure() 
ax = plt.axes(xlim=(-1, 1), ylim=(-1, 1),) 
triangle, = ax.fill([0,1,1],[0,0,1]) 
# I want to change the datapoints later in my code, like this: 
triangle.set_data([0,2,2],[0,0,2]) 

请您参考如下方法:

这没有特别详细的文档记录,但是 Polygon 对象有一对方法 get_xy 和 set_xy。 get_xy() 方法返回一个形状为 (N + 1, 2) 的 ndarray。额外的点是第一个点的重复(因此多边形是闭合的)。将所需数据放入预期格式(这是文档中指定的构造 Polygon 对象的格式):

triangle.set_xy(np.array([[0, 2, 2, 0],[0, 0, 2, 0]]).T) 
ax = plt.gca() 
ax.set_xlim([0, 3]) 
ax.set_ylim([0, 3]) 
plt.draw() 

这甚至可以让您更改面片中的顶点数。

添加问题以澄清文档 https://github.com/matplotlib/matplotlib/issues/3035 .