通過Plotly實現(xiàn)交互式數(shù)據(jù)可視化的流程步驟
通過Plotly實現(xiàn)交互式數(shù)據(jù)可視化的步驟
在數(shù)據(jù)科學和數(shù)據(jù)分析領域,數(shù)據(jù)可視化是一種非常重要的技術(shù)。Plotly 是一個功能強大的 Python 可視化庫,它可以幫助我們創(chuàng)建交互式的數(shù)據(jù)可視化圖表。本文將介紹如何使用 Plotly 實現(xiàn)交互式數(shù)據(jù)可視化,包括數(shù)據(jù)準備、圖表創(chuàng)建和交互功能的添加。
步驟
1. 安裝 Plotly
首先,確保已經(jīng)安裝了 Plotly。如果沒有安裝,可以使用 pip 進行安裝:
pip install plotly
2. 準備數(shù)據(jù)
在進行數(shù)據(jù)可視化之前,需要準備好要可視化的數(shù)據(jù)。在本示例中,我們將使用一個簡單的數(shù)據(jù)集。
import pandas as pd # 創(chuàng)建示例數(shù)據(jù) data = { 'Year': [2015, 2016, 2017, 2018, 2019], 'Sales': [100, 150, 200, 250, 300] } df = pd.DataFrame(data)
3. 創(chuàng)建交互式圖表
使用 Plotly 來創(chuàng)建交互式圖表非常簡單。下面是一個簡單的例子,創(chuàng)建一個折線圖:
import plotly.graph_objs as go # 創(chuàng)建折線圖 trace = go.Scatter(x=df['Year'], y=df['Sales'], mode='lines', name='Sales') # 創(chuàng)建布局 layout = go.Layout(title='Yearly Sales', xaxis=dict(title='Year'), yaxis=dict(title='Sales')) # 創(chuàng)建圖表對象 fig = go.Figure(data=[trace], layout=layout) # 顯示圖表 fig.show()
4. 添加交互功能
Plotly 提供了豐富的交互功能,可以讓用戶與圖表進行互動。例如,我們可以添加鼠標懸停提示信息:
# 添加鼠標懸停提示信息 trace = go.Scatter(x=df['Year'], y=df['Sales'], mode='lines', name='Sales', hoverinfo='x+y', line=dict(color='blue')) # 創(chuàng)建布局 layout = go.Layout(title='Yearly Sales', xaxis=dict(title='Year'), yaxis=dict(title='Sales')) # 創(chuàng)建圖表對象 fig = go.Figure(data=[trace], layout=layout) # 顯示圖表 fig.show()
5. 更多交互功能
除了鼠標懸停提示信息之外,Plotly 還支持許多其他交互功能,如縮放、平移、選擇和標記等。你可以根據(jù)需要添加這些功能來提升用戶體驗。
import pandas as pd import plotly.graph_objs as go # 創(chuàng)建示例數(shù)據(jù) data = { 'Year': [2015, 2016, 2017, 2018, 2019], 'Sales': [100, 150, 200, 250, 300] } df = pd.DataFrame(data) # 創(chuàng)建折線圖 trace = go.Scatter(x=df['Year'], y=df['Sales'], mode='lines', name='Sales', hoverinfo='x+y', line=dict(color='blue')) # 創(chuàng)建布局 layout = go.Layout(title='Yearly Sales', xaxis=dict(title='Year'), yaxis=dict(title='Sales')) # 創(chuàng)建圖表對象 fig = go.Figure(data=[trace], layout=layout) # 顯示圖表 fig.show()
6. 導出圖表
一旦你創(chuàng)建了交互式的圖表,你可能想要將它導出到文件中以供分享或嵌入到網(wǎng)頁中。Plotly 提供了多種導出圖表的方法,包括靜態(tài)圖片和交互式 HTML 文件。
導出靜態(tài)圖片
# 導出為靜態(tài)圖片 fig.write_image("sales_plot.png")
導出為 HTML 文件
# 導出為 HTML 文件 fig.write_html("sales_plot.html")
這樣,你就可以輕松地將交互式圖表分享給其他人或者嵌入到網(wǎng)頁中。
import pandas as pd import plotly.graph_objs as go # 創(chuàng)建示例數(shù)據(jù) data = { 'Year': [2015, 2016, 2017, 2018, 2019], 'Sales': [100, 150, 200, 250, 300] } df = pd.DataFrame(data) # 創(chuàng)建折線圖 trace = go.Scatter(x=df['Year'], y=df['Sales'], mode='lines', name='Sales', hoverinfo='x+y', line=dict(color='blue')) # 創(chuàng)建布局 layout = go.Layout(title='Yearly Sales', xaxis=dict(title='Year'), yaxis=dict(title='Sales')) # 創(chuàng)建圖表對象 fig = go.Figure(data=[trace], layout=layout) # 添加交互功能 fig.update_layout( xaxis=dict( rangeselector=dict( buttons=list([ dict(count=1, label="1年", step="year", stepmode="backward"), dict(count=2, label="2年", step="year", stepmode="backward"), dict(count=3, label="3年", step="year", stepmode="backward"), dict(count=4, label="4年", step="year", stepmode="backward"), dict(step="all") ]) ), rangeslider=dict(visible=True), type="date" ) ) # 導出為靜態(tài)圖片 fig.write_image("sales_plot.png") # 導出為 HTML 文件 fig.write_html("sales_plot.html") # 顯示圖表 fig.show()
通過以上步驟,你可以輕松地創(chuàng)建、定制并分享交互式的數(shù)據(jù)可視化圖表,為數(shù)據(jù)分析工作增添更多的樂趣和效率!
7. 自定義圖表樣式
Plotly 允許你對圖表樣式進行高度定制,以滿足特定需求或者提升可視化效果。
修改線條樣式
# 修改線條樣式 trace = go.Scatter(x=df['Year'], y=df['Sales'], mode='lines+markers', name='Sales', hoverinfo='x+y', line=dict(color='blue', width=2), marker=dict(size=8, color='red'))
調(diào)整布局
# 調(diào)整布局 layout = go.Layout(title='Yearly Sales', xaxis=dict(title='Year', showgrid=False), yaxis=dict(title='Sales', showgrid=False))
添加標題和標簽
# 添加標題和標簽 fig.update_layout(title_text="Yearly Sales", xaxis_title="Year", yaxis_title="Sales")
通過以上調(diào)整,你可以根據(jù)需要自定義圖表的外觀和布局。
import pandas as pd import plotly.graph_objs as go # 創(chuàng)建示例數(shù)據(jù) data = { 'Year': [2015, 2016, 2017, 2018, 2019], 'Sales': [100, 150, 200, 250, 300] } df = pd.DataFrame(data) # 創(chuàng)建折線圖 trace = go.Scatter(x=df['Year'], y=df['Sales'], mode='lines+markers', name='Sales', hoverinfo='x+y', line=dict(color='blue', width=2), marker=dict(size=8, color='red')) # 創(chuàng)建布局 layout = go.Layout(title='Yearly Sales', xaxis=dict(title='Year', showgrid=False), yaxis=dict(title='Sales', showgrid=False)) # 創(chuàng)建圖表對象 fig = go.Figure(data=[trace], layout=layout) # 添加交互功能 fig.update_layout( xaxis=dict( rangeselector=dict( buttons=list([ dict(count=1, label="1年", step="year", stepmode="backward"), dict(count=2, label="2年", step="year", stepmode="backward"), dict(count=3, label="3年", step="year", stepmode="backward"), dict(count=4, label="4年", step="year", stepmode="backward"), dict(step="all") ]) ), rangeslider=dict(visible=True), type="date" ) ) # 添加標題和標簽 fig.update_layout(title_text="Yearly Sales", xaxis_title="Year", yaxis_title="Sales") # 導出為靜態(tài)圖片 fig.write_image("sales_plot.png") # 導出為 HTML 文件 fig.write_html("sales_plot.html") # 顯示圖表 fig.show()
通過以上步驟,你可以更加靈活地定制和分享交互式的數(shù)據(jù)可視化圖表!
總結(jié)
在這篇文章中,我們學習了如何使用 Plotly 實現(xiàn)交互式數(shù)據(jù)可視化的步驟。以下是我們探討的主要內(nèi)容:
安裝 Plotly:首先,我們確保安裝了 Plotly 庫,它是一個功能強大的 Python 可視化庫。
準備數(shù)據(jù):在進行數(shù)據(jù)可視化之前,我們需要準備好要可視化的數(shù)據(jù)。我們使用了一個簡單的示例數(shù)據(jù)集作為演示。
創(chuàng)建交互式圖表:我們使用 Plotly 創(chuàng)建了一個交互式折線圖,并學習了如何調(diào)整布局和添加交互功能,例如鼠標懸停提示信息和范圍選擇器。
導出圖表:我們還學習了如何將交互式圖表導出為靜態(tài)圖片或 HTML 文件,以便分享或嵌入到網(wǎng)頁中。
自定義圖表樣式:最后,我們探討了如何自定義圖表樣式,包括修改線條樣式、調(diào)整布局以及添加標題和標簽,以滿足特定需求或提升可視化效果。
通過以上步驟,你可以輕松地創(chuàng)建、定制并分享交互式的數(shù)據(jù)可視化圖表,為數(shù)據(jù)分析工作增添更多的樂趣和效率!
拓展:Plotly實現(xiàn)數(shù)據(jù)可視化的五種動圖形式
啟動
如果你還沒安裝 Plotly,只需在你的終端運行以下命令即可完成安裝:
pip install plotly
安裝完成后,就開始使用吧!
動畫
在研究這個或那個指標的演變時,我們常涉及到時間數(shù)據(jù)。Plotly 動畫工具僅需一行代碼就能讓人觀看數(shù)據(jù)隨時間的變化情況,如下圖所示:
代碼如下:
import plotly.express as px from vega\_datasets import data df = data.disasters() df = df\[df.Year > 1990\] fig = px.bar(df, y="Entity", x="Deaths", animation\_frame="Year", orientation='h', range\_x=\[0, df.Deaths.max()\], color="Entity") # improve aesthetics (size, grids etc.) fig.update\_layout(width=1000, height=800, xaxis\_showgrid=False, yaxis\_showgrid=False, paper\_bgcolor='rgba(0,0,0,0)', plot\_bgcolor='rgba(0,0,0,0)', title\_text='Evolution of Natural Disasters', showlegend=False) fig.update\_xaxes(title\_text='Number of Deaths') fig.update\_yaxes(title\_text='') fig.show()
只要你有一個時間變量來過濾,那么幾乎任何圖表都可以做成動畫。下面是一個制作散點圖動畫的例子:
import plotly.express as px df = px.data.gapminder() fig = px.scatter( df, x="gdpPercap", y="lifeExp", animation\_frame="year", size="pop", color="continent", hover\_name="country", log\_x=True, size\_max=55, range\_x=\[100, 100000\], range\_y=\[25, 90\], # color\_continuous\_scale=px.colors.sequential.Emrld ) fig.update\_layout(width=1000, height=800, xaxis\_showgrid=False, yaxis\_showgrid=False, paper\_bgcolor='rgba(0,0,0,0)', plot\_bgcolor='rgba(0,0,0,0)')
太陽圖
太陽圖(sunburst chart)是一種可視化 group by 語句的好方法。如果你想通過一個或多個類別變量來分解一個給定的量,那就用太陽圖吧。
假設我們想根據(jù)性別和每天的時間分解平均小費數(shù)據(jù),那么相較于表格,這種雙重 group by 語句可以通過可視化來更有效地展示。
這個圖表是交互式的,讓你可以自己點擊并探索各個類別。你只需要定義你的所有類別,并聲明它們之間的層次結(jié)構(gòu)(見以下代碼中的 parents 參數(shù))并分配對應的值即可,這在我們案例中即為 group by 語句的輸出。
import plotly.graph\_objects as go import plotly.express as px import numpy as np import pandas as pd df = px.data.tips() fig = go.Figure(go.Sunburst( labels=\["Female", "Male", "Dinner", "Lunch", 'Dinner ', 'Lunch '\], parents=\["", "", "Female", "Female", 'Male', 'Male'\], values=np.append( df.groupby('sex').tip.mean().values, df.groupby(\['sex', 'time'\]).tip.mean().values), marker=dict(colors=px.colors.sequential.Emrld)), layout=go.Layout(paper\_bgcolor='rgba(0,0,0,0)', plot\_bgcolor='rgba(0,0,0,0)')) fig.update\_layout(margin=dict(t=0, l=0, r=0, b=0), title\_text='Tipping Habbits Per Gender, Time and Day') fig.show()
現(xiàn)在我們向這個層次結(jié)構(gòu)再添加一層:
為此,我們再添加另一個涉及三個類別變量的 group by 語句的值。
import plotly.graph\_objects as go import plotly.express as px import pandas as pd import numpy as np df = px.data.tips() fig = go.Figure(go.Sunburst(labels=\[ "Female", "Male", "Dinner", "Lunch", 'Dinner ', 'Lunch ', 'Fri', 'Sat', 'Sun', 'Thu', 'Fri ', 'Thu ', 'Fri ', 'Sat ', 'Sun ', 'Fri ', 'Thu ' \], parents=\[ "", "", "Female", "Female", 'Male', 'Male', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Lunch', 'Lunch', 'Dinner ', 'Dinner ', 'Dinner ', 'Lunch ', 'Lunch ' \], values=np.append( np.append( df.groupby('sex').tip.mean().values, df.groupby(\['sex', 'time'\]).tip.mean().values, ), df.groupby(\['sex', 'time', 'day'\]).tip.mean().values), marker=dict(colors=px.colors.sequential.Emrld)), layout=go.Layout(paper\_bgcolor='rgba(0,0,0,0)', plot\_bgcolor='rgba(0,0,0,0)')) fig.update\_layout(margin=dict(t=0, l=0, r=0, b=0), title\_text='Tipping Habbits Per Gender, Time and Day') fig.show()
平行類別
另一種探索類別變量之間關(guān)系的方法是以下這種流程圖。你可以隨時拖放、高亮和瀏覽值,非常適合演示時使用。
代碼如下:
import plotly.express as px from vega\_datasets import data import pandas as pd df = data.movies() df = df.dropna() df\['Genre\_id'\] = df.Major\_Genre.factorize()\[0\] fig = px.parallel\_categories( df, dimensions=\['MPAA\_Rating', 'Creative\_Type', 'Major\_Genre'\], color="Genre\_id", color\_continuous\_scale=px.colors.sequential.Emrld, ) fig.show()
平行坐標圖
平行坐標圖是上面的圖表的連續(xù)版本。這里,每一根弦都代表單個觀察。這是一種可用于識別離群值(遠離其它數(shù)據(jù)的單條線)、聚類、趨勢和冗余變量(比如如果兩個變量在每個觀察上的值都相近,那么它們將位于同一水平線上,表示存在冗余)的好用工具。
代碼如下:
import plotly.express as px from vega\_datasets import data import pandas as pd df = data.movies() df = df.dropna() df\['Genre\_id'\] = df.Major\_Genre.factorize()\[0\] fig = px.parallel\_coordinates( df, dimensions=\[ 'IMDB\_Rating', 'IMDB\_Votes', 'Production\_Budget', 'Running\_Time\_min', 'US\_Gross', 'Worldwide\_Gross', 'US\_DVD\_Sales' \], color='IMDB\_Rating', color\_continuous\_scale=px.colors.sequential.Emrld) fig.show()
量表圖和指示器
量表圖僅僅是為了好看。在報告 KPI 等成功指標并展示其與你的目標的距離時,可以使用這種圖表。
指示器在業(yè)務和咨詢中非常有用。它們可以通過文字記號來補充視覺效果,吸引觀眾的注意力并展現(xiàn)你的增長指標。
import plotly.graph\_objects as go fig = go.Figure(go.Indicator( domain = {'x': \[0, 1\], 'y': \[0, 1\]}, value = 4.3, mode = "gauge+number+delta", title = {'text': "Success Metric"}, delta = {'reference': 3.9}, gauge = {'bar': {'color': "lightgreen"}, 'axis': {'range': \[None, 5\]}, 'steps' : \[ {'range': \[0, 2.5\], 'color': "lightgray"}, {'range': \[2.5, 4\], 'color': "gray"}\], })) fig.show()
到此這篇關(guān)于通過Plotly實現(xiàn)交互式數(shù)據(jù)可視化的流程步驟的文章就介紹到這了,更多相關(guān)Plotly交互式數(shù)據(jù)可視化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python內(nèi)置random模塊生成隨機數(shù)的方法
這篇文章主要介紹了Python內(nèi)置random模塊生成隨機數(shù)的方法,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-05-05關(guān)于pandas.DataFrame的類SQL操作
這篇文章主要介紹了關(guān)于pandas.DataFrame的類SQL操作方式,具有很好的參考價值,希望對大家有所幫助,2023-08-08Python報錯TypeError: ‘dict‘ object is not&
在Python開發(fā)的旅程中,報錯信息就像是一個個路障,阻礙著我們前進的步伐,而“TypeError: ‘dict’ object is not iterable”這個報錯,常常讓開發(fā)者們陷入困惑,那么,這個報錯究竟是怎么產(chǎn)生的呢?又該如何有效地解決它呢?讓我們一起深入探討,找到解決問題的方法2024-10-10剛學完怎么用Python實現(xiàn)定時任務,轉(zhuǎn)頭就跑去撩妹!
朋友問我有沒有定時任務的模塊,并且越簡單越好.剛好前今天就研究了一下定時任務模塊,于是就告訴他使用方式,令我沒有想到的是,這貨他學會了之后,居然買了一個服務器給女朋友發(fā)消息,發(fā)消息,發(fā)消息……重要的事情說三遍,需要的朋友可以參考下2021-06-06python模擬點擊網(wǎng)頁按鈕實現(xiàn)方法
在本篇文章里小編給大家整理的是一篇關(guān)于python模擬點擊網(wǎng)頁按鈕實現(xiàn)方法,需要的朋友們可以參考下。2020-02-02Anaconda虛擬環(huán)境中安裝cudatoolkit和cudnn包并配置tensorflow-gpu的教程
這篇文章詳細介紹了如何在Anaconda虛擬環(huán)境中配置PyTorch和TensorFlow-GPU,并提供了詳細的步驟和注意事項,通過圖文講解的非常詳細,需要的朋友可以參考下2025-02-02