gallamine
gallamine

Reputation: 875

programmatically change matplotlib fill data

I'm creating an animation using Matplotlib and I'm using a Fill object. I'd like to be able to change the fill data from a function. For other plot types there's usually a set_data() function or set_offsets(). Fill doesn't seem to have one. I would expect to do something like the code below but this doesn't work. Any ideas?

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])

Upvotes: 3

Views: 968

Answers (1)

tacaswell
tacaswell

Reputation: 87376

This is not particularly well documented, but Polygon objects have a pair of methods get_xy and set_xy. The method get_xy() returns an ndarray with shape (N + 1, 2). The extra point is a repeat of the first point (so that the polygon is closed). Putting the desired data into the expected format (which is what is specified in the documentation to construct a Polygon object):

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()

This even lets you change the number of vertices in your patch.

Added issue to clarify the documentation https://github.com/matplotlib/matplotlib/issues/3035.

Upvotes: 2

Related Questions