16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 21 ■ PROJECT 2: PAINTING A PRETTY PICTURE 415<br />

Constructing Some PolyLines<br />

To create a line diagram (a graph) of the sunspot data, you have <strong>to</strong> create some lines. In fact,<br />

you have <strong>to</strong> create several lines that are linked. ReportLab has a special class for this: PolyLine.<br />

A PolyLine is created with a list of coordinates as its first argument. This list is of the form<br />

[(x0, y0), (x1, y1), ...], with each pair of x and y coordinates making one point on the<br />

PolyLine. See Figure 21-2 for a simple PolyLine.<br />

Figure 21-2. PolyLine([(0, 0), (10, 0), (10, 10), (0, 10)])<br />

To make a line diagram, one polyline must be created for each column in the data set.<br />

Each point in these polylines will consist of a time (constructed from the year and month) and<br />

a value (which is the number of sunspots taken from the relevant column). To get one of the<br />

columns (the values), list comprehensions can be useful:<br />

pred = [row[2] for row in data]<br />

Here pred (for “predicted”) will be a list of all the values in the third column of the data.<br />

You can use a similar strategy for the other columns. (The time for each row would have <strong>to</strong> be<br />

calculated from both the year and month: for example, year + month/12.)<br />

Once you have the values and the time stamps, you can add your polylines <strong>to</strong> the drawing<br />

like this:<br />

drawing.add(PolyLine(zip(times, pred), strokeColor=colors.blue))<br />

It isn’t necessary <strong>to</strong> set the stroke color, of course, but it makes it easier <strong>to</strong> tell the lines<br />

apart. (Note how zip is used <strong>to</strong> combine the times and values in<strong>to</strong> a list of tuples.)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!