matplotlib之Basemap与PyQt4一例

有网友发消息提问:

我现在想做个小软件,软件上能够绘等值线(等值线在地图上),用到了basemap,需要将matplotlib的basemap嵌入到pyqt的画布中,查了很多资料,能够将pyqt的简单的xy坐标嵌入到pyqt中,但是不能够将basemap嵌入。不知道你能不能给点意见呢?

实在是惭愧,尽管简单看过一点点PyQt4和matplotlib,却连basemap是什么东西都不知道。

遇事不决,找google...

Basemap

简单说:它是matplotlib提供的用于在地图上绘制二维数据的工具。

  • The matplotlib basemap toolkit is a library for plotting 2D data on maps in Python. It is similar in functionality to the matlab mapping toolbox, the IDL mapping facilities, GrADS, or the Generic Mapping Tools. PyNGL and CDAT are other libraries that provide similar capabilities in Python.

安装

它不是matplotlib默认安装的一部分(源码竟然包竟然100M以上,难怪不被默认包含)。所以需要我们自己动手安装:

源码仓库:

https://github.com/matplotlib/basemap

通过git或者直接下载压缩的源码包。而后解压,查看README

我使用的Ubuntu 11.04,先安装一些东西

sudo apt-get install python-matplotlib swig python2.7-dev

而后按照安装说明:

  • 进入 GEOS 子目录
./configure --enable-python
make
sudo make install
  • 回到顶级目录
sudo python setup.py install

运行例子

按照README,运行例子确认安装是否成功,切换到examples目录,运行simpletest.py

matplotlib之Basemap与PyQt4一例_第1张图片

python simpletest.py

嵌入到PyQt4

  • basemap 例子中有一个wxpython的例子 embedding_map_in_wx.py
  • 我们参考它写一个pyqt4的例子,先跑起来再说

matplotlib之Basemap与PyQt4一例_第2张图片

 

代码如下:

"""
An example of how to use Basemap in pyqt4 application.

Copyright(C) 2011 dbzhang800#gmail.com
"""

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from mpl_toolkits.basemap import Basemap
from PyQt4 import QtGui

class Widget(FigureCanvas):
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=100)
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)
        self.axes = fig.add_subplot(111)

        map = Basemap(ax=self.axes)
        map.drawcoastlines()
        map.drawcountries()
        map.drawmapboundary()
        map.fillcontinents(color='coral', lake_color='aqua')
        map.drawmapboundary(fill_color='aqua')

        self.setWindowTitle("PyQt4 and Basemap -- dbzhang800")

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

参考

  • http://matplotlib.sourceforge.net/basemap/doc/html/index.html

  • http://matplotlib.sourceforge.net/basemap/doc/html/api/basemap_api.html

  • http://www.scipy.org/Cookbook/Matplotlib/Maps

  • http://matplotlib.sourceforge.net/examples/user_interfaces/embedding_in_qt4.html

  • http://hi.baidu.com/cyclone/blog/item/527dd21bbd73e7d8ad6e759c.html

 

你可能感兴趣的:(PyQt4/PySide,Python)