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交互式繪圖主要工具包
一些例子