這兩天看了一下數據可視化工具plotly,感覺還不錯,比matplotlib炫酷多了,在此記錄一下簡單用法。
介紹plotly
plotly是一款基于D3.js框架的Python庫,所以功能肯定很強大、炫酷。結合jupyter notebook效果更好。pip安裝
pip install plotly
以為pip安裝一下就行了,迫不及待就去跑示例代碼,結果報錯,提示沒有登錄什么的,了解之后才知道,plotly有兩種模式。
離線模式:沒有數量限制,圖片都在本地。
在線模式:最多可以上傳25張,可以通過瀏覽器在線編輯、觀看。更好的分享給別,有分為三種情況——公開(public)、私人(private)、秘密(secret)。
在線plotly
首先需要注冊一個plotly的賬戶,然后可以看到自己的Username和API Keys,放到代碼里面就可以作圖了。
import plotly
plotly.tools.set_credentials_file(username='yourAccount', api_key='u8U00uFdqKcYH5qykuu4')
plotly.tools.set_config_file(world_readable=True,
sharing='public')
import plotly.plotly as py
import plotly.graph_objs as go
trace0 = go.Scatter(
x=[1, 2, 3, 4],
y=[10, 15, 13, 17]
)
trace1 = go.Scatter(
x=[1, 2, 3, 4],
y=[16, 5, 11, 9]
)
data = [trace0, trace1]
py.plot(data, filename = 'basic-line', auto_open=True)
上面會輸出一個網址,打開就可以看到了。最厲害的是竟然可以直接在線可視化編輯,厲害了!更多功能自己點擊左側按鈕實驗吧。
離線模式
大部分我們還是使用離線模式,比較在線模式有數量限制,還得打開網頁才能看到,其中離線模式我喜歡在jupyter notebook中使用。
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
plot([go.Scatter(x=[1, 2, 3], y=[3, 1, 6])])
輸出'file:///data/notebook/dataVisualization/temp-plot.html',是一個HTML,不是很方便,使用iplot畫圖就方便多了
init_notebook_mode(connected=True)# 設置為離線模式
iplot([{"x": [1, 2, 3], "y": [3, 1, 6]}])
直接輸出圖片了。
舉幾個例子
在jupyter notebook輸出會有縮放、移動、截圖等功能按鈕,但是markdown不能顯示,就簡單截個圖吧。
Plotly的核心是一個數據可視化工具箱,每個plotly圖像的背后都是一個JSON對象,一個類似字典的數據結構。僅僅通過修改這個對象的一些關鍵字,就可以得到非常不同的、詳細的圖。例如:
import plotly.offline as py
import plotly.graph_objs as go
py.init_notebook_mode(connected=True)
trace1 = go.Scatter(x=[1,2,3], y=[4,5,6], marker={'color': 'red', 'symbol': 104, 'size': 10},
mode="markers+lines", text=["one","two","three"], name='1st Trace')
layout=go.Layout(title="First Plot", xaxis={'title':'x1'}, yaxis={'title':'x2'})
figure=go.Figure(data=[trace1],layout=layout)
py.iplot(figure, filename='pyguide_1')
figure
輸出
Figure({
'data': [{'marker': {'color': 'red', 'size': 10, 'symbol': 104},
'mode': 'markers+lines',
'name': '1st Trace',
'text': [one, two, three],
'type': 'scatter',
'uid': '6e76d08b-2f9b-429e-ae31-0d2faeb41e78',
'x': [1, 2, 3],
'y': [4, 5, 6]}],
'layout': {'title': {'text': 'First Plot'}, 'xaxis': {'title': {'text': 'x1'}}, 'yaxis': {'title': {'text': 'x2'}}}
})
可以看到我們使用py.iplot畫的圖確實是一個類似于字典的對象,此外,我們可以通過添加/定義與散點圖相關的關鍵字的值,來修改這個圖片。
如果我們想改變散點圖的標題,同時使用綠色的先代替紅色的先,可以通過Plot update來實現。
figure.update(dict(layout=dict(title='Plot update'), data=[dict(marker=dict(color='blue'))]))
py.iplot(figure, filename='pyguide_2')
此外,Plotly plots 是交互式的,這意味著你可以在圖像上通過平移、選擇、縮放來手動操作探索數據。
很快你就能弄明白如何以你想要的方式繪制圖表,怎么分享這些信息給你想分享的人。例如,我們可以快速查看一下如何定義生成散點圖所需的對象,以比較兩個大陸之間的預期壽命了人均GDP。
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/yankev/test/master/life-expectancy-per-GDP-2007.csv')
americas = df[(df.continent=='Americas')]
europe = df[(df.continent=='Europe')]
trace_comp0 = go.Scatter(
x=americas.gdp_percap,
y=americas.life_exp,
mode='markers',
marker=dict(size=12,
line=dict(width=1),
color="navy"
),
name='Americas',
text=americas.country,
)
trace_comp1 = go.Scatter(
x=europe.gdp_percap,
y=europe.life_exp,
mode='markers',
marker=dict(size=12,
line=dict(width=1),
color="red"
),
name='Europe',
text=europe.country,
)
data_comp = [trace_comp0, trace_comp1]
layout_comp = go.Layout(
title='Life Expectancy v. Per Capita GDP, 2007',
hovermode='closest',
xaxis=dict(
title='GDP per capita (2000 dollars)',
ticklen=5,
zeroline=False,
gridwidth=2,
),
yaxis=dict(
title='Life Expectancy (years)',
ticklen=5,
gridwidth=2,
),
)
fig_comp = go.Figure(data=data_comp, layout=layout_comp)
py.iplot(fig_comp, filename='life-expectancy-per-GDP-2007')
希望這能讓您了解如果使用Plotly Python Library繪制圖表,稍后,我們將在后面的章節詳細介紹構成這個圖表的不同部分。但是現在,我希望您能看到它的可定制性,以及我們如何通過編程定義這些圖。
Plotly強大能力的來源
Plotly生成的所有圖表實際上都是plotly.js這個javascript庫產生的,無論是在瀏覽器還是Ipython notebook中,所有的可視化、交互都是基于plot.js,plot.js建立在d3.js和stack.gl之上,plotly.js是一個高級的聲明性圖表庫,提供了20多種圖表類型,包含了3D圖表、統計圖和SVG地圖。
使用Python API
Python API是一個設計用來和Plotly.js庫交互的包,以便允許Python用戶在他們喜歡的環境中創建繪圖。這個包提供函數和圖形對象,可以簡化圖形生成的過程,這相當于在JSON對象中正確定義關鍵字(如上面的例子所示),這將允許我們以函數的方式創建我們的圖。所以我們來分解一下。
import plotly.offline as py
import plotly.graph_objs as go
為了生成我們的Plotly圖表,我們需要兩個主要的模塊。
. plotly.offline
包含了與Plotly服務器通信的功能。
. plotly.graph_objs
包含了生成圖表對象的函數
注意:如果我們檢查上一節中的示例代碼,我們可以看到下面的部分。
. Data
. Layout
. Figure
DATA
go.Scatter(x=[1,2,3], y=[4,5,6], marker={'color': 'red', 'symbol': 104, 'size': "10"},
mode="markers+lines", text=["one","two","three"])
輸出
Scatter({
'marker': {'color': 'red', 'size': 10, 'symbol': 104},
'mode': 'markers+lines',
'text': [one, two, three],
'x': [1, 2, 3],
'y': [4, 5, 6]
})
定義了一個散點圖的軌跡,此外,它定制了我們需要繪制的數據,即3個數據點(1,4),(2,5),(3,6),以及繪制該數據相關的規范。在這個例子中,我們想把這些點畫成空閑的x,用紅色的線把他們串起來。
此外,我們還可以向數據列表中,添加另一個散點對象,我們可以通過定義一個新的散點對象來實現這一點,并將其包含到數據對象的定義中。
import numpy as np
x = np.arange(1,3.2,0.2)
y = 6*np.sin(x)
y
輸出
array([5.04882591, 5.59223452, 5.91269838, 5.99744162, 5.84308579,
5.45578456, 4.85097842, 4.05277908, 3.09300823, 2.0099289 ,
0.84672005])
輸出
trace2 = go.Scatter(x=x, y=y, marker={'color': 'blue', 'symbol': 'star', 'size': 10}, mode='markers', name='2nd trace')
data = go.Data([trace1, trace2])
data
輸出
[Scatter({
'marker': {'color': 'red', 'size': 10, 'symbol': 104},
'mode': 'markers+lines',
'name': '1st Trace',
'text': [one, two, three],
'x': [1, 2, 3],
'y': [4, 5, 6]
}), Scatter({
'marker': {'color': 'blue', 'size': 10, 'symbol': 'star'},
'mode': 'markers',
'name': '2nd trace',
'x': array([1. , 1.2, 1.4, 1.6, 1.8, 2. , 2.2, 2.4, 2.6, 2.8, 3. ]),
'y': array([5.04882591, 5.59223452, 5.91269838, 5.99744162, 5.84308579, 5.45578456,
4.85097842, 4.05277908, 3.09300823, 2.0099289 , 0.84672005])
})]
plot2 = py.iplot(go.Figure(data=data, layout=layout), filename='pyguide_3')
plot2
Layout
這個Layout就是定義圖的外觀,以及與數據無關的圖功能。因此,我們可以改變標題、軸標題、間距、字體等。
layout=go.Layout(title="First Plot", xaxis={'title':'x1'}, yaxis={'title':'x2'})
layout
輸出
{'title': 'First Plot', 'xaxis': {'title': 'x1'}, 'yaxis': {'title': 'x2'}}
Annotations
我們為軸添加了標題,還添加一個一個文本注釋,指出最大點。
layout.update(dict(annotations=[go.Annotation(text="Highest Point", x=3, y=6)]))
py.iplot(go.Figure(data=data, layout=layout), filename='pyguide_4')
推薦一篇與pandas結合的文章,寫的很好。The Next Level of Data Visualization in Python
參考
Getting Started with Plotly for Python
Plotly User Guide in Python
官方文檔