一文學(xué)會制作 6 種炫酷的 Python 動態(tài)圖
很多時候,一張炫酷圖就足以勝過千言萬語。對于數(shù)學(xué)科學(xué)家來說,當(dāng)想闡述自己的觀點、勞動成果時,我們需要直接有效的溝通。單調(diào)乏味的文本和數(shù)字,很難抓住別人的眼球,飄飄亮亮的可視化動態(tài)圖是必不可少的,至少是一個加分項。
本文將基于Python的Plotly圖形庫,介紹幾種工作中常用的動畫圖和交互式圖標(biāo)。在使用之前看一下是否安裝了 Plotly。
1. 朝陽圖
層次結(jié)構(gòu)數(shù)據(jù)通常存儲為矩形數(shù)據(jù)框,其中不同的列對應(yīng)于層次結(jié)構(gòu)的不同級別。px.sunburst可以采用path與列列表相對應(yīng)的參數(shù)。請注意,如果給出id,則parent不應(yīng)提供path。
- import plotly.express as px
- df = px.data.tips()
- fig = px.sunburst(df, path=['day', 'time', 'sex'], values='total_bill')
- fig.show()
2. ?;鶊D
?;鶊D通過定義可視化到流動的貢獻源來表示源節(jié)點,目標(biāo)為目標(biāo)節(jié)點,數(shù)值以設(shè)置流volum,和標(biāo)簽,顯示了節(jié)點名稱,在流量分析中常用。
- import plotly.graph_objects as go
- import urllib, json
- url = 'https://raw.githubusercontent.com/plotly/plotly.js/master/test/image/mocks/sankey_energy.json'
- response = urllib.request.urlopen(url)
- data = json.loads(response.read())
- # override gray link colors with 'source' colors
- opacity = 0.4
- # change 'magenta' to its 'rgba' value to add opacity
- data['data'][0]['node']['color'] = ['rgba(255,0,255, 0.8)' if color == "magenta" else color for color in data['data'][0]['node']['color']]
- data['data'][0]['link']['color'] = [data['data'][0]['node']['color'][src].replace("0.8", str(opacity))
- for src in data['data'][0]['link']['source']]
- fig = go.Figure(data=[go.Sankey(
- valueformat = ".0f",
- valuesuffix = "TWh",
- # Define nodes
- node = dict(
- pad = 15,
- thickness = 15,
- line = dict(color = "black", width = 0.5),
- label = data['data'][0]['node']['label'],
- color = data['data'][0]['node']['color']
- ),
- # Add links
- link = dict(
- source = data['data'][0]['link']['source'],
- target = data['data'][0]['link']['target'],
- value = data['data'][0]['link']['value'],
- label = data['data'][0]['link']['label'],
- color = data['data'][0]['link']['color']
- ))])
- fig.update_layout(title_text="Energy forecast for 2050<br>Source: Department of Energy & Climate Change, Tom Counsell via <a >Mike Bostock</a>",
- font_size=10)
- fig.show()
效果圖

3. 雷達圖
雷達圖(也稱為蜘蛛情節(jié)或情節(jié)星)顯示器在從中心軸始發(fā)表示定量變量的二維圖的形式多變量數(shù)據(jù)。軸的相對位置和角度通常是無用的。它等效于軸沿徑向排列的平行坐標(biāo)圖。
- import plotly.graph_objects as go
- import urllib, json
- url = 'https://raw.githubusercontent.com/plotly/plotly.js/master/test/image/mocks/sankey_energy.json'
- response = urllib.request.urlopen(url)
- data = json.loads(response.read())
- # override gray link colors with 'source' colors
- opacity = 0.4
- # change 'magenta' to its 'rgba' value to add opacity
- data['data'][0]['node']['color'] = ['rgba(255,0,255, 0.8)' if color == "magenta" else color for color in data['data'][0]['node']['color']]
- data['data'][0]['link']['color'] = [data['data'][0]['node']['color'][src].replace("0.8", str(opacity))
- for src in data['data'][0]['link']['source']]
- fig = go.Figure(data=[go.Sankey(
- valueformat = ".0f",
- valuesuffix = "TWh",
- # Define nodes
- node = dict(
- pad = 15,
- thickness = 15,
- line = dict(color = "black", width = 0.5),
- label = data['data'][0]['node']['label'],
- color = data['data'][0]['node']['color']
- ),
- # Add links
- link = dict(
- source = data['data'][0]['link']['source'],
- target = data['data'][0]['link']['target'],
- value = data['data'][0]['link']['value'],
- label = data['data'][0]['link']['label'],
- color = data['data'][0]['link']['color']
- ))])
- fig.update_layout(title_text="Energy forecast for 2050<br>Source: Department of Energy & Climate Change, Tom Counsell via <a >Mike Bostock</a>",
- font_size=10)
- fig.show()
效果圖

4. 漏斗圖
漏斗圖通常用于表示業(yè)務(wù)流程不同階段的數(shù)據(jù)。在商業(yè)智能中,這是識別流程潛在問題區(qū)域的重要機制。例如,它用于觀察銷售過程中每個階段的收入或損失,并顯示逐漸減小的值。每個階段均以占所有值的百分比表示。
- from plotly import graph_objects as go
- fig = go.Figure()
- fig.add_trace(go.Funnel(
- name = 'Montreal',
- y = ["Website visit", "Downloads", "Potential customers", "Requested price"],
- x = [120, 60, 30, 20],
- textinfo = "value+percent initial"))
- fig.add_trace(go.Funnel(
- name = 'Toronto',
- orientation = "h",
- y = ["Website visit", "Downloads", "Potential customers", "Requested price", "invoice sent"],
- x = [100, 60, 40, 30, 20],
- textposition = "inside",
- textinfo = "value+percent previous"))
- fig.add_trace(go.Funnel(
- name = 'Vancouver',
- orientation = "h",
- y = ["Website visit", "Downloads", "Potential customers", "Requested price", "invoice sent", "Finalized"],
- x = [90, 70, 50, 30, 10, 5],
- textposition = "outside",
- textinfo = "value+percent total"))
- fig.show()
效果圖

5. 3D表面圖
具有輪廓的曲面圖,使用contours屬性顯示和自定義每個軸的輪廓數(shù)據(jù)。
- import plotly.graph_objects as go
- import pandas as pd
- # Read data from a csv
- z_data = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/api_docs/mt_bruno_elevation.csv')
- fig = go.Figure(data=[go.Surface(z=z_data.values)])
- fig.update_traces(contours_z=dict(show=True, usecolormap=True,
- highlightcolor="limegreen", project_z=True))
- fig.update_layout(title='Mt Bruno Elevation', autosize=False,
- scene_camera_eye=dict(x=1.87, y=0.88, z=-0.64),
- width=500, height=500,
- margin=dict(l=65, r=50, b=65, t=90)
- )
- fig.show()
6. 動畫圖
一些Plotly Express函數(shù)支持通過animation_frame和animation_group參數(shù)創(chuàng)建動畫人物。這是使用Plotly Express創(chuàng)建的動畫散點圖的示例。請注意,您應(yīng)始終修復(fù)x_range和,y_range以確保您的數(shù)據(jù)在整個動畫中始終可見。
- import plotly.express as px
- df = px.data.gapminder()
- px.scatter(df, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country",
- size="pop", color="continent", hover_name="country",
- log_x=True, size_max=55, range_x=[100,100000], range_y=[25,90])
結(jié)論
可視化的圖形在日常工作中經(jīng)常實用,其中Plotly是用過的體驗比較好的,本篇文章分享給大家一些案例,Plotly可視化遠不止這些,在后續(xù)的文章中,涉及可視化部分的,將介紹更多酷炫的可視化圖形,喜歡點個在看分享,收藏以備不時之需。