python交互式绘图–Pygal(一)
在利用python处理数据时,一份动态的可交互的图标常常能让我们更加自由的探索数据。Pygal工具包就为我们提供了这样的工具,可以在绘图后交互地观察数据,更加直观生动的感受一图胜千言的美妙。
本文内容包括:
- 安装pygal
- Hello world demo
- Jupyter中使用pygal
1.安装
对于Pygal可以使用pip进行安装:
pip install pygal
2.初体验
安装好了就可以开始画图了,首先我们画一柱状图来作为演示:
import pygal # 导入 pygal bar_chart = pygal.Bar() # 创建一个换图对象 bar_chart.add('FirsrtTry', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]) # 添加一些值和对应的序列 bar_chart.add('SecondTry', [55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0]) # 再添加另一个序列 bar_chart.render_to_file('bar_chart.svg') # Save the svg to a file`
随后在运行目录下就可以看到bar_char.svg
的图像文件了。
3.在Jupyter中使用Pygal
很多情况下我们需要在jupyter中使用图表功能,那么就需要自己设置一个渲染选项,将生成的交互svg
图加载到jupyter中:
#首先需要定义一个html渲染对象 html_pygal = '<!DOCTYPE html><html><head><script type="text/javascript" src="http://kozea.github.com/pygal.js/javascripts/svg.jquery.js"></script><script type="text/javascript" src="http://kozea.github.com/pygal.js/javascripts/pygal-tooltips.js"></script></head><body><figure>{pygal_render}</figure></body></html>' #或者写成这样的格式 html_pygal = """ <!DOCTYPE html> <html> <head> <script type="text/javascript" src="http://kozea.github.com/pygal.js/javascripts/svg.jquery.js"></script> <script type="text/javascript" src="http://kozea.github.com/pygal.js/javascripts/pygal-tooltips.js"></script> <!-- 加载对应的js工具 --> <!-- from http://ino.pm/blog/ipython-pygal/#.W6XBCkxuJPZ --> </head> <body> <figure> {pygal_render} <!-- 这里定义的渲染对象的输入 --> </figure> </body> </html> """
然后需要导入交互式绘图包:
import sys reload(sys) sys.setdefaultencoding('utf-8') #这里是为了防止windows下编码错误 import pygal from IPython.display import SVG, display,HTML #导入交互式绘图包 %matplotlib inline
我们再重复一下刚刚的作图步骤,稍微修代码:
bar_chart = pygal.Bar() # 创建一个换图对象 bar_chart.add('FirsrtTry', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]) # 添加一些值和对应的序列 bar_chart.add('SecondTry', [55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0]) # 再添加另一个序列 HTML(html_pygal.format(pygal_render=bar_chart.render())) #这里直接用render(),而无需render_to_file() #此时,HTML工具利用刚刚定义的html_pygal 就可以加载对应的js来处理,在jupyter中实现interaction了
from ino.pm
- 还有一种更简便的方法
from IPython.display import SVG, display #利用display模块来现实 display({'image/svg+xml': bar_chart.render()}, raw=True)
ref:
官方文档
Python交互式绘图主要工具包
一些例子