python3基础教程 项目2:绘制图表

比较简单的一个小项目,不需要太多讲解。

URI和URL的区别可以看下https://blog.csdn.net/mengzhongdaima/article/details/81351695

直接上代码吧

from urllib.request 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 = 'ftp://ftp.swpc.noaa.gov/pub/weekly/Predict.txt'
COMMENT_CHARS = '#:'

drawing = Drawing(400,200)
data = []
for line in urlopen(URL).readlines():
    line = line.decode() #解码为Unicode
    if not line.isspace() and line[0] not 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 = [list(zip(times,pred)),
            list(zip(times,high)),
            list(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')

运行结果(和书上不同,因为网站上数据在随着时间改变): 

 python3基础教程 项目2:绘制图表_第1张图片

你可能感兴趣的:(Python基础)