I've made an animation that is supposed to show a Japanese hiragana character being drawn. To that end I am using a clip path so that my drawn line will only fill out a predetermined area. However, the clip path doesn't seem to do anything. It's not returning any errors and the clip patch is just not being applied in the animation. What am I doing wrong?
import matplotlib.pyplot as plt
from svgpath2mpl import parse_path
from matplotlib.patches import PathPatch
from matplotlib.animation import FuncAnimation
clip_patch = "M181 359C174 359 165 363 166 371C167 382 176 389 183 396C198 412 199 435 204 455C222 538 238 623 276 700C300 745 333 786 374 816C385 824 400 826 411 818C418 814 420 805 420 797C421 780 417 762 420 745C422 720 430 696 436 671C437 666 438 657 431 654C424 652 417 658 414 664C399 686 387 710 372 731C370 734 366 735 364 732C347 718 331 702 319 683C303 658 294 629 285 601C276 570 267 538 260 506C254 477 250 448 249 419C249 409 254 399 253 389C251 379 240 375 232 370C216 363 199 359 181 359Z"
stroke_path = "M 174,370 218,397 276,642 316,734 394,801 396,733 423,673"
clip_patch = parse_path(clip_patch)
stroke_path = parse_path(stroke_path)
fig, ax = plt.subplots()
ax.plot([],[],'k',lw=15)
ax.set_clip_path(clip_patch,transform=ax.transData)
clip_patch = PathPatch(clip_patch,fc=(0.3,0.3,0.3,0.3),ec=(0,0,0,0))
ax.add_patch(clip_patch)
def init():
ax.set_xlim(0,1024)
ax.set_ylim(0,1024)
ax.set_aspect('equal')
ax.invert_yaxis()
return ax.lines
def update(frame):
x = stroke_path.vertices[:frame,0]
y = stroke_path.vertices[:frame,1]
ax.lines[0].set_data(x,y)
return ax.lines
ani = FuncAnimation(fig, update, frames=len(stroke_path),init_func=init, blit=True)
plt.show()
As is, the line is being drawn, but the clip path (which is indicated in grey) doesn't actually clip the black line.
You need to set the clip path of the line, not of the axes:
line, = ax.plot([], [],'k',lw=15)
line.set_clip_path(clip_patch, transform=ax.transData)
PS: in FuncAnimation, it should be frames=len(stroke_path) + 1
to draw the complete line