數據分析離不開數據可視化。我們最常用的就是pandas,matplotlib,pyecharts當然還有Tableau,看到一篇文章介紹plotly制圖后我也躍躍欲試,查看了相關資料開始學習plotly.
Plotly 是一款用來做數據分析和可視化的在線平台,功能非常強大,可以在線繪制很多圖形比如條形圖、散點圖、餅圖、直方圖等等。而且還是支持在線編輯,以及多種語言python、javascript、matlab、R等許多API,當然我們這里主要介紹Python語言,可以直接用pip install plotly即可。

plotly可以畫出很多媲美Tableau的高質量圖,我嘗試做了折線圖、散點圖和直方圖,代碼如下:
首先導入庫
from plotly.graph_objs import Scatter,Layout import plotly import plotly.offline as py import numpy as np import plotly.graph_objs as go #setting offilne plotly.offline.init_notebook_mode(connected=True) # 上面幾行代碼主要是引用一些庫,最重要的一點是要把plotly設置為offline模式,
1.折線圖
N = 100 random_x = np.linspace(0,1,N) random_y0 = np.random.randn(N)+5 random_y1 = np.random.randn(N) random_y2 = np.random.randn(N)-5 #Create traces trace0 = go.Scatter( x = random_x, y = random_y0, mode = 'markers', name = 'markers' ) trace1 = go.Scatter( x = random_x, y = random_y1, mode = 'lines+markers', name = 'lines+markers' ) trace2 = go.Scatter( x = random_x, y = random_y2, mode = 'lines', name = 'lines' ) data = [trace0,trace1,trace2] py.iplot(data) # 隨機設置4個參數,x軸的數字和y軸,其中y軸隨機3組數據。 # 然后畫三種類型的圖,trace0是markers,trace1是折線圖和markers,trace3是折線圖。 # 然后把三種圖放在data這個列表里面,調用py.iplot(data)即可。

2.散點圖
trace1 = go.Scatter( y = np.random.randn(500), mode = 'markers', marker = dict( size = 16, color = np.random.randn(500), colorscale = 'Viridis', showscale = True ) ) data = [trace1] py.iplot(data,filename='scatter-plot-with-colorscale') # 這個是mode設置為markers就是散點圖,然后marker里面設置一組參數, # 比如顏色的隨機范圍,散點的大小,還有圖例等等。最后一行里面的filename是在當前目錄下生成html文件

3.直方圖
trace0 = go.Bar( x = ['Jan','Feb','Mar','Apr', 'May','Jun', 'Jul','Aug','Sep','Oct','Nov','Dec'], y = [20,14,25,16,18,22,19,15,12,16,14,17], name = 'Primary Product', marker=dict( color = 'rgb(49,130,189)' ) ) trace1 = go.Bar( x = ['Jan','Feb','Mar','Apr', 'May','Jun', 'Jul','Aug','Sep','Oct','Nov','Dec'], y = [19,14,22,14,16,19,15,14,10,12,12,16], name = 'Secondary Product', marker=dict( color = 'rgb(204,204,204)' ) ) data = [trace0,trace1] py.iplot(data)

上面的制圖只是plotly的冰山一角,都是一些最基本的用法,它還有很多很酷的用法和圖形,尤其是跟pandas結合畫的圖非常漂亮,比如一些股票的K線圖,大家有興趣可以研究研究~
鏈接:https://plot.ly/python/
