PYTHON基础教程中十个项目(2)

第二个项目没有第一个项目难度那么大了,作者估计也是想让大家了解一下python可以利用一些图形包画图,然后输出到一个pdf文件,具体如果想使用比如reportlab这种图形包的更多功能还要去查阅文档


源码下载:https://github.com/Harkphoenix/Python2


hellp_report.py

# coding=utf-8
from reportlab.graphics.shapes import Drawing, String
from reportlab.graphics import renderPDF

d = Drawing(100,100)    #创建100*100大小的图纸
s = String(50,50,"hello world", textAnchor = "middle")   #在整个图纸的什么位置,如何显示文本
d.add(s)                                             #把文本放置在图纸上
renderPDF.drawToFile(d, 'hello.pdf', 'a simple pdf file')         #在本地目录下输出一个pdf文件

sunpots_roto.py


from reportlab.lib import colors
from reportlab.graphics.shapes import *
from reportlab.graphics import renderPDF

data = [
(2013 ,12        ,76.4    ,77.4    ,75.4),
(2014 ,1        ,78.6    ,80.6    ,76.6),
(2014 ,2        ,80.1    ,83.1    ,77.1),
(2014 ,3        ,82.4    ,87.4    ,77.4),
(2014 ,4        ,83.7    ,88.7    ,78.7),
(2014 ,5        ,83.1    ,89.1    ,77.1),
(2014 ,6        ,82.3    ,89.3    ,75.3)
]

drawing = Drawing(200,300)
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) - 2013) - 110 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,'Sunports', fontsize = 18, fillColor = colors.red))

renderPDF.drawToFile(drawing, "report3.pdf", 'Sunports')

最终程序:

import urllib
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://www.swpc.noaa.gov/ftpdir/weekly/Predict.txt"
COMMENT_CHARS = '#:'

drawing = Drawing(600,400)
data = []
html = urllib.urlopen(url).readlines()

for line in html:
	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 = 100
lp.y = 100
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(350,250,'Subspots', fontsize = 14, fileColor = colors.red))
renderPDF.drawToFile(drawing, "report7.pdf", 'Sunports')


你可能感兴趣的:(PYTHON基础教程中十个项目(2))