想上手一款Python數據可視化庫來給你的數據分析結果繪制一系列賞心悅目的圖表?是時候了解一下交互式可視化庫Plotly了。
Plotly介紹
Plotly包是一個基於plotly.js (而plotly.js又基於d3.js)的開源交互式圖形繪制Python包,可以生成離線html格式(能在瀏覽器中顯示)的交互式圖表,或者保存結果在雲端服務器(https://plotly.com/)以便在線查看,共享。
Plotly本身也是一家主要提供機器學習和數據科學模型前端圖形顯示產品的公司。Plotly包提供了數十種高質量,交互式圖表類型,詳見https://plotly.com/python/。
下面舉例說明幾種個人比較常用的圖表:
1. 散點圖
生成兩組正態分布隨機數作散點圖和折線圖
import pandas as pd
import numpy as np
from plotly.offline import plot as plot_ly
import plotly.graph_objs as go
N = 50
random_x = np.linspace(0, 1, N)
random_y0 = np.random.randn(N)
random_y1 = np.random.randn(N) +3
trace0 = go.Scatter( x = random_x, y = random_y0, mode = 'markers', name = 'markers')
trace1 = go.Scatter( x = random_x, y = random_y1, mode = 'lines', name = 'lines')
#mode還可以是markers+lines
data = [trace0, trace1]
plot_ly(data, filename='./Scatter.html') #生成結果為Scatter.html
2.雙軸圖
類似於上例的數據,我們稍作修改以生成另一個類型的圖標
random_y0 = abs(np.random.randn(N))
random_y1 = abs(np.random.randn(N)) * 100
trace0 = go.Scatter(x=random_x, y=random_y0, mode='lines+markers', name='Y1')
trace1 = go.Bar(x=random_x, y=random_y1, name='Y2', yaxis="y2",opacity=0.7) #柱狀圖對象y軸為y2, 圖形透明度為0.7
data = [trace0, trace1]
layout = go.Layout(title="ScatterL+BarR",
yaxis=dict(title="Y1"),
yaxis2=dict(title="Y2", overlaying='y', side="right"),
legend=dict(x=0, y=1, font=dict(size=12, color="black"))) #設置標題及字體
fig = go.Figure(data=data, layout=layout)
plot_ly(fig, filename='bar.html')
3.環形餅圖
labels = ['BuildFail','Aborted','Success','SmokeTestFail','SelenaFail','Other','CheckoutFail','StaticCheckFail']
values = [17,18,12,6,7,8,10,21]
trace = [go.Pie( labels = labels, values = values, hole = 0.5,
hoverinfo = "label + percent")] #hole即為中間洞的大小,hoverinfo為鼠標懸停在圖表上顯示的內容
layout = go.Layout( title = 'Build Status' )
fig = go.Figure(data = trace, layout = layout)
plot_ly(fig, filename='pie.html')
4.旭日圖
基於上例的數據稍作修改,我們就可以做出旭日圖
labels = ['BuildFail','Aborted','Success','SmokeTestFail','SelenaFail','Other','CheckoutFail','StaticCheckFail','Fail','OtherP','SuccessP']
parents = ['Fail','OtherP','SuccessP','Fail','Fail','OtherP','Fail','Fail','','','']
values = [17,18,12,6,7,8,10,21,51,26,12]
trace = [go.Sunburst (
labels = labels,
parents = parents,
values = values)]
layout=go.Layout( plot_bgcolor='#E6E6FA',paper_bgcolor='#F8F8FF')
fig = go.Figure(data = trace, layout = layout)
plot_ly(fig, filename='Sunburst.html')
旭日圖為是餅圖的拓展,點擊父級可以僅展示該父級及其子集。
5. 雷達圖
import plotly.express as px #plotly.express是對plotly.py的高級封裝,可以為復雜的圖表提供簡單的語法
import pandas as pd
df = pd.DataFrame(dict(
r=[2, 5, 4, 1, 3],
theta=['Architecture','Integration','Simulation', 'Tooling', 'Jenkins']))
fig = px.line_polar(df, r='r', theta='theta', line_close=True)
plot_ly(fig, filename='radar.html')
總結
以上的例子演示的都是離線下的Plotly作圖,如果需要在線繪圖只需多一個注冊免費賬號獲取API key的步驟,這里不做展開。Plotly無疑是我目前用過的Python圖形包中可視化效果最好,功能最齊全,語法最簡單的一款。希望它能幫到你。:)