Using A List Comprehension

It's also possible to implement the star patch with list comprehensions. The idea is to zip together the elements in the polygon list:

def another_star(R, xO, yO, color='w', N=5, thin=0.5):

Returns an N-pointed star of size R at (xO, yO) (matplotlib patch)

r*cos(a+pi/N)+xO, r*sin(a+pi/N)+yO)) return Polygon(polystar.reshape(N*2, 2), fc=color, ec=color)

Some would prefer this implementation over the previous implementation. Personally, I think both are fine; choose whichever is easier for you to follow.

It's also possible to code the entire function as a single return statement, but I strongly recommend against it, as the code would be hard to understand.

The script in Listing 9-9 generates some interesting stars.

Listing 9-9. Generating Some Interesting Stars

# show some star examples from pylab import *

# ensure the star patch is defined properly execfile('star_patch.py')

for i, example in enumerate(examples): subplot(2, 2, i+l) exec "new_star="+example gca().add_patch(new_star) title(example) axis('scaled') axis([-10, 10, -10, 10])

In this script I've decided to iterate over a list of strings and use the exec statement. The same string used for the exec statement is also used to create the title for the subplots (see Figure 9-6).

-10 -5 0 5 10

Figure 9-6. Some star patches

Was this article helpful?

0 0

Post a comment