Python專案之畫幅好畫

這個專案是《Python基礎教程》後面的專案之一。這個專案主要是用來學習如何在Python中建立圖形,具體說就是利用圖形建立一個PDF檔案,使從文字中讀取的資料視覺化。要想實現,就得先下載影象生成包,可以在http://www.reportlab.org下載安裝包,然後安裝在Python所在路徑中即可使用。

初步版本:

實現了基本內容。

實現程式碼:

from reportlab.lib import colors
from reportlab.graphics.shapes import *
from reportlab.graphics import renderPDF
data = [  
#    Year   Month   Predicted   High    Low  
(2007, 8, 113.2, 114.2, 112.2),  
(2007, 9, 112.8, 115.8, 109.8),  
(2007, 10, 111.0, 116.0, 106.0),  
(2007, 11, 109.8, 116.8, 102.8),  
(2007, 12, 107.3, 115.3, 99.3),  
(2008, 1, 105.2, 114.2, 96.2),  
(2008, 2, 104.1, 114.1, 94.1),  
(2008, 3, 99.9, 110.9, 88.9),  
(2008, 4, 94.8, 106.8, 82.8),  
(2008, 5, 91.2, 104.2, 78.2),   
] 
drawing = Drawing(200, 150)
pred = [row[2]-40 for row in data]
high = [row[3]-40 for row in data]
low = [row[4]-40 for row in data]
times = [200*((row[0]   row[1]/12.0) - 2007)-100 for row in data]
drawing.add(PolyLine(zip(times, pred), strokeColor = colors.blue))  
drawing.add(PolyLine(zip(times, high), strokeColor = colors.red))  
drawing.add(PolyLine(zip(times, low), strokeColor = colors.green))  
drawing.add(String(65, 115, 'Sunspots', fonSize = 18, fillColor = colors.red))  
renderPDF.drawToFile(drawing, 'report1.pdf', 'Sunspots')

執行結果:

最終版本:

使用了標準模板urllib可以從網上獲取檔案,以及使用了LinePlot類以使當發生變化時,為了讓內容處於正確的位置不必做專門的修改。

實現程式碼:

from urllib import urlopen
from reportlab.graphics.shapes import *
from reportlab.graphics.charts.lineplots import LinePlot
from reportlab.graphics.charts.textlabels import Label
from reportlab.graphics import renderPDF
URL = 'http://services.swpc.noaa.gov/text/predicted-sunspot-radio-flux.txt'
COMMENT_CHARS = '#:'
drawing = Drawing(400, 200)
data = []
for line in urlopen(URL).readlines():
if not line.isspace() and not line[0] in COMMENT_CHARS:
data.append([float(n) for n in line.split()])
pred = [row[2] for row in data]
high = [row[3] for row in data]
low = [row[4] for row in data]
times = [row[0]   row[1]/12.0 for row in data]
lp = LinePlot()
lp.x = 50
lp.y = 50
lp.height = 125
lp.width = 300
lp.data = [zip(times, pred),zip(times,high),zip(times, low)]
lp.lines[0].strokeColor = colors.blue
lp.lines[1].strokeColor = colors.red
lp.lines[2].strokeColor = colors.green
drawing.add(lp)
drawing.add(String(250,150, 'Sunspots',fontSize=14,fillColor=colors.red))
renderPDF.drawToFile(drawing, 'report2.pdf','Sunspots')

執行結果:

Python真是一門功能強大的語言,繼續探索它更多的奧祕吧。