Example Adding Arrows to a Graph

In this example we'll draw a graph and connect every two points on the graph with an arrow. First draw a simple graph:

>>> x = arange(io) ยป> y = x**2 >>> plot(x, y)

Now create a list of all the arrows:

>>> ars = [(xO, yO, dx, dy) for (xO, yO, dx, dy) in zip(x, y, diff(x), diff(y))]

This is a bit tricky. First, the function diff() creates a difference of every two elements in a vector, for example, diff([l, 2, 3, 30]) is [l, 1, 27]. This is exactly what we need for our dx and dy values for the Arrow() function. Second, we combine x, y, dx, and dy using the zip() function and return a list of tuples by using a list comprehension. Luckily for us, zip() uses the shortest vector, so even though diff() vectors are shorter by 1, it's not an issue.

Now, all that's left is to iterate through the list comprehension and attach an arrow to the graph:

Figure 6-17 shows the added arrows.

Figure 6-17. Patching arrows

Needless to say, Arrow(), as well as other patches, can be customized considerably; you can adjust color, length, width, and more.

Was this article helpful?

0 0

Post a comment