Python交互式绘图——Pygal绘图包(一、安装及入门)


python交互式绘图–Pygal(一)

在利用python处理数据时,一份动态的可交互的图标常常能让我们更加自由的探索数据。Pygal工具包就为我们提供了这样的工具,可以在绘图后交互地观察数据,更加直观生动的感受一图胜千言的美妙。
本文内容包括:

  • 安装pygal
  • Hello world demo
  • Jupyter中使用pygal
安装
Pygal
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交互式绘图主要工具包
一些例子


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM