“Beginning Python”(六)“Plot”

来源:互联网 发布:淘宝客服交流技巧 编辑:程序博客网 时间:2024/05/18 00:02

    本文主要介绍《Beginning Python》中的“Project 2 : Painting a Pretty Picture”,通过这个工程,读者可以学习到以下知识:

1)简单的“数据可视化”

2)python画图

3)几个python库:reportlab、urllib、pyx、wxpython、matplotlib/pylab


一、项目综述

    这个项目主要演示如何用python进行数据分析和数据可视化。它选取的是:从“Space Weather Prediction Center”的网站上(http://www.swpc.noaa.gov/)获取一份“data about sunspots”(太阳黑子数据),并将这份数据画出“polyline chart”(多段线图),然后导出为PDF文件。数据和图如下:

1)部分数据样本

# Predicted Sunspot Number And Radio Flux Values# With Expected Ranges## -----Sunspot Number------ ----10.7 cm Radio Flux----# YR MO    PREDICTED    HIGH    LOW    PREDICTED    HIGH     LOW#--------------------------------------------------------------2007 12      4.8        5.0     4.7       67.6       70.4    64.72008 01      4.3        4.4     4.2       66.7       69.5    63.82008 02      4.0        4.1     3.9       66.1       68.9    63.22008 03      4.2        4.3     4.0       65.7       68.6    62.82008 04      4.6        4.8     4.4       65.7       68.6    62.72008 05      5.2        5.6     4.9       65.6       68.7    62.52008 06      5.8        6.3     5.2       65.2       68.5    62.02008 07      6.3        7.1     5.5       64.9       68.4    61.42008 08      7.4        8.6     6.3       65.1       68.9    61.22008 09      8.6        10.2    7.0       65.4       69.6    61.2

注:实际数据网址是:ftp://ftp.swpc.noaa.gov/pub/weekly/Predict.txt

2)多段线图

                                 


注:这是从PDF文件中截取的,实际生成的是一个PDF文件。


二、探索ReportLab和urllib

    这个工程中主要用到了两个python模块:reportlab和urllib。此外,作者也提到了可以使用pxy、wxpython和matplotlib来替代reportlab。下面先来探索一下这个几个库。


1,Exploring Modules

    《Beginning Python》第10章“Exploring Modules”介绍了几个通用的探索python模块的方法:

1)检查某个module是否安装

>> import reportlab


    如果在python环境下输入该命令不报错,则该module存在,如果不存在,可以先用简单的pip命令安装

2)查看文件目录

>> [n for n in dir(reportlab) if not n.startswith('_')]

    这里用到了dir()函数和“list comprehension”(chapter 5)。此外,以下划线(underscore)开头的文件表示它不想被外部调用,可以屏蔽这类文件。


3)查看文档和路径

    事实上,直接用dir()函数可以发现许多以下划线开头的文件,其中“__path__”表示路径,“__doc__”表示文档,可以如下调用:

>> reportlab.__doc__


>> reportlab.__path__

4)查看函数帮助——help()函数




2,网络搜索

    除此之外,最有效的方式是直接在网上搜索相关文档,例如:

python官网文档:https://www.python.org/doc/

python在线库搜索:https://www.python.org/search/?q=reportlab

附几个库的网址:

1)https://www.reportlab.com/

2)http://pyx.sourceforge.net/

3)http://matplotlib.org/

这几个网站有非常详细的介绍和源码示例。


三、源码分析

    这个工程的源码比较简单,如下:

#sunspots.pyfrom urllib.request import urlopenfrom reportlab.graphics.shapes import *from reportlab.graphics.charts.lineplots import LinePlotfrom reportlab.graphics.charts.textlabels import Labelfrom reportlab.graphics import renderPDFURL = '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()    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 = 50lp.y = 50lp.height = 125lp.width = 300lp.data = [list(zip(times, pred)),           list(zip(times, high)),           list(zip(times, low))]lp.lines[0].strokeColor = colors.bluelp.lines[1].strokeColor = colors.redlp.lines[2].strokeColor = colors.greendrawing.add(lp)drawing.add(String(250, 150, 'Sunspots',            fontSize=14, fillColor=colors.red))renderPDF.drawToFile(drawing, 'report2.pdf', 'Sunspots')

1,导入模块

    2-6行主要是导入所需要的库,其中urllib是一个用于处理url的模块,它包括:urllib.request用于像文件一样打开和读URLs,urllib.parse用于解析URLs等待。这些信息都可以在python官网的doc子网中找到。

    ReportLab貌似还没有加入标准库,可以直接登录它的开发网站学习,上面有很多示例。它最主要包括:画图和生成pdf文档两大功能。其中shapes中包含“Drawing”和“String”,chart一看就知道是画图表的。


2,获取数据

    8-17行主要是获取数据。

    其中,第14行的意思是:通过urlopen()函数打开一个网址(网络文件),这个函数返回一个文件流对象,然后再调用readlines()函数,返回“行迭代器”,最后用for循环按行迭代该网络文件。

    第15行,将字节流(二进制)转换为字符串。参考:

bytes.decode(encoding="utf-8",errors="strict")
bytearray.decode(encoding="utf-8",errors="strict")

Return a string decoded from the given bytes. Default encoding is'utf-8'. errors may be given to set a different error handling scheme. The default forerrors is 'strict', meaning that encoding errors raise aUnicodeError. Other possible values are'ignore', 'replace' and any other name registered viacodecs.register_error(), see sectionError Handlers. For a list of possible encodings, see section Standard Encodings.


    第16行是过滤非数据行。

    第17行将字符串转换为float型的数据list。


3,数据处理

    这个工程要画“polyline chart”,就需要x轴坐标数据和y轴坐标数据,19-22行用于获取这两类数据。

    这里要画三条线,y轴有三份数据,x轴共一份数据。y轴的数据很好获得,直接使用list comprehension,将列向量变成行向量。x轴则需要将单位统一化。


4,画图

    24-40行都是画图代码。

    第12行定义了一个Drawing实例,它可以看作是canvas(画布),这是一个矩形画布,初始化值是它的长和宽。

    第24行构造了一个LinePlot实例,然后设置它的属性,其中x和y是原点位置(the bottom left centre)。最后将LinePlot加入到Drawing中。

    关于LinePlot,可以参考ReportLab的文档userguide的11.8节。

    此外,如果想快速画图,也可以调用“PolyLine”,如下:

drawing.add(PolyLine(list(zip(times, pred)), strokeColor=colors.blue))drawing.add(PolyLine(list(zip(times, high)), strokeColor=colors.red))drawing.add(PolyLine(list(zip(times, low)), strokeColor=colors.green))drawing.add(String(65, 115, 'Sunspots', fontSize=18, fillColor=colors.red))renderPDF.drawToFile(drawing, 'report1.pdf', 'Sunspots')

四、扩展

    除了ReportLab,本文来提到了pyx、wxpython、matplotlib几个画图库。现在,我们就来一一探索一下。

1,pyx

    http://pyx.sourceforge.net/

    PyX is a Python package for the creation of PostScript, PDF, and SVG files. It combines an abstraction of the PostScript drawing model with a TeX/LaTeX interface. Complex tasks like 2d and 3d plots in publication-ready quality are built out of these primitives.

    它的用法和ReportLab很像。


2,wxpython

    https://wxpython.org/

     wxPython is a GUI toolkit for thePython programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module (native code) that wraps the popular wxWidgets cross platform GUI library, which is written in C++. 

    它是C++和python混合编程的画图库。

    

3,matplotlib

    http://matplotlib.org/

    Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. Matplotlib can be used in Python scripts, the Python andIPython shell, the jupyter notebook, web application servers, and four graphical user interface toolkits.

    Matplotlib tries to make easy things easy and hard things possible. You can generate plots, histograms, power spectra, bar charts, errorcharts, scatterplots, etc., with just a few lines of code. For a sampling, see thescreenshots,thumbnail gallery, andexamples directory

    For simple plotting the pyplot module provides a MATLAB-like interface, particularly when combined withIPython. For the power user, you have full control of line styles, font properties, axes properties, etc, via an object oriented interface or via a set of functions familiar to MATLAB users.

    它的pyplot模块提供了类似matlab的语法。

    它的gallery里有上百幅缩略图,点开了就可以看到源码。方便用户快速找到要绘制的图的模版和源码。