通過(guò)Plotly實(shí)現(xiàn)交互式數(shù)據(jù)可視化的流程步驟
通過(guò)Plotly實(shí)現(xiàn)交互式數(shù)據(jù)可視化的步驟
在數(shù)據(jù)科學(xué)和數(shù)據(jù)分析領(lǐng)域,數(shù)據(jù)可視化是一種非常重要的技術(shù)。Plotly 是一個(gè)功能強(qiáng)大的 Python 可視化庫(kù),它可以幫助我們創(chuàng)建交互式的數(shù)據(jù)可視化圖表。本文將介紹如何使用 Plotly 實(shí)現(xiàn)交互式數(shù)據(jù)可視化,包括數(shù)據(jù)準(zhǔn)備、圖表創(chuàng)建和交互功能的添加。
步驟
1. 安裝 Plotly
首先,確保已經(jīng)安裝了 Plotly。如果沒(méi)有安裝,可以使用 pip 進(jìn)行安裝:
pip install plotly
2. 準(zhǔn)備數(shù)據(jù)
在進(jìn)行數(shù)據(jù)可視化之前,需要準(zhǔn)備好要可視化的數(shù)據(jù)。在本示例中,我們將使用一個(gè)簡(jiǎn)單的數(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 來(lái)創(chuàng)建交互式圖表非常簡(jiǎn)單。下面是一個(gè)簡(jiǎn)單的例子,創(chuàng)建一個(gè)折線圖:
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)建圖表對(duì)象 fig = go.Figure(data=[trace], layout=layout) # 顯示圖表 fig.show()
4. 添加交互功能
Plotly 提供了豐富的交互功能,可以讓用戶與圖表進(jìn)行互動(dòng)。例如,我們可以添加鼠標(biāo)懸停提示信息:
# 添加鼠標(biāo)懸停提示信息
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)建圖表對(duì)象
fig = go.Figure(data=[trace], layout=layout)
# 顯示圖表
fig.show()
5. 更多交互功能
除了鼠標(biāo)懸停提示信息之外,Plotly 還支持許多其他交互功能,如縮放、平移、選擇和標(biāo)記等。你可以根據(jù)需要添加這些功能來(lái)提升用戶體驗(yàn)。
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)建圖表對(duì)象
fig = go.Figure(data=[trace], layout=layout)
# 顯示圖表
fig.show()
6. 導(dǎo)出圖表
一旦你創(chuàng)建了交互式的圖表,你可能想要將它導(dǎo)出到文件中以供分享或嵌入到網(wǎng)頁(yè)中。Plotly 提供了多種導(dǎo)出圖表的方法,包括靜態(tài)圖片和交互式 HTML 文件。
導(dǎo)出靜態(tài)圖片
# 導(dǎo)出為靜態(tài)圖片
fig.write_image("sales_plot.png")
導(dǎo)出為 HTML 文件
# 導(dǎo)出為 HTML 文件
fig.write_html("sales_plot.html")
這樣,你就可以輕松地將交互式圖表分享給其他人或者嵌入到網(wǎng)頁(yè)中。
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)建圖表對(duì)象
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"
)
)
# 導(dǎo)出為靜態(tài)圖片
fig.write_image("sales_plot.png")
# 導(dǎo)出為 HTML 文件
fig.write_html("sales_plot.html")
# 顯示圖表
fig.show()
通過(guò)以上步驟,你可以輕松地創(chuàng)建、定制并分享交互式的數(shù)據(jù)可視化圖表,為數(shù)據(jù)分析工作增添更多的樂(lè)趣和效率!
7. 自定義圖表樣式
Plotly 允許你對(duì)圖表樣式進(jìn)行高度定制,以滿足特定需求或者提升可視化效果。
修改線條樣式
# 修改線條樣式
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))
添加標(biāo)題和標(biāo)簽
# 添加標(biāo)題和標(biāo)簽 fig.update_layout(title_text="Yearly Sales", xaxis_title="Year", yaxis_title="Sales")
通過(guò)以上調(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)建圖表對(duì)象
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"
)
)
# 添加標(biāo)題和標(biāo)簽
fig.update_layout(title_text="Yearly Sales", xaxis_title="Year", yaxis_title="Sales")
# 導(dǎo)出為靜態(tài)圖片
fig.write_image("sales_plot.png")
# 導(dǎo)出為 HTML 文件
fig.write_html("sales_plot.html")
# 顯示圖表
fig.show()
通過(guò)以上步驟,你可以更加靈活地定制和分享交互式的數(shù)據(jù)可視化圖表!
總結(jié)
在這篇文章中,我們學(xué)習(xí)了如何使用 Plotly 實(shí)現(xiàn)交互式數(shù)據(jù)可視化的步驟。以下是我們探討的主要內(nèi)容:
安裝 Plotly:首先,我們確保安裝了 Plotly 庫(kù),它是一個(gè)功能強(qiáng)大的 Python 可視化庫(kù)。
準(zhǔn)備數(shù)據(jù):在進(jìn)行數(shù)據(jù)可視化之前,我們需要準(zhǔn)備好要可視化的數(shù)據(jù)。我們使用了一個(gè)簡(jiǎn)單的示例數(shù)據(jù)集作為演示。
創(chuàng)建交互式圖表:我們使用 Plotly 創(chuàng)建了一個(gè)交互式折線圖,并學(xué)習(xí)了如何調(diào)整布局和添加交互功能,例如鼠標(biāo)懸停提示信息和范圍選擇器。
導(dǎo)出圖表:我們還學(xué)習(xí)了如何將交互式圖表導(dǎo)出為靜態(tài)圖片或 HTML 文件,以便分享或嵌入到網(wǎng)頁(yè)中。
自定義圖表樣式:最后,我們探討了如何自定義圖表樣式,包括修改線條樣式、調(diào)整布局以及添加標(biāo)題和標(biāo)簽,以滿足特定需求或提升可視化效果。
通過(guò)以上步驟,你可以輕松地創(chuàng)建、定制并分享交互式的數(shù)據(jù)可視化圖表,為數(shù)據(jù)分析工作增添更多的樂(lè)趣和效率!
拓展:Plotly實(shí)現(xiàn)數(shù)據(jù)可視化的五種動(dòng)圖形式
啟動(dòng)
如果你還沒(méi)安裝 Plotly,只需在你的終端運(yùn)行以下命令即可完成安裝:
pip install plotly
安裝完成后,就開(kāi)始使用吧!
動(dòng)畫(huà)
在研究這個(gè)或那個(gè)指標(biāo)的演變時(shí),我們常涉及到時(shí)間數(shù)據(jù)。Plotly 動(dòng)畫(huà)工具僅需一行代碼就能讓人觀看數(shù)據(jù)隨時(shí)間的變化情況,如下圖所示:

代碼如下:
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()
只要你有一個(gè)時(shí)間變量來(lái)過(guò)濾,那么幾乎任何圖表都可以做成動(dòng)畫(huà)。下面是一個(gè)制作散點(diǎn)圖動(dòng)畫(huà)的例子:
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)')
太陽(yáng)圖
太陽(yáng)圖(sunburst chart)是一種可視化 group by 語(yǔ)句的好方法。如果你想通過(guò)一個(gè)或多個(gè)類(lèi)別變量來(lái)分解一個(gè)給定的量,那就用太陽(yáng)圖吧。
假設(shè)我們想根據(jù)性別和每天的時(shí)間分解平均小費(fèi)數(shù)據(jù),那么相較于表格,這種雙重 group by 語(yǔ)句可以通過(guò)可視化來(lái)更有效地展示。

這個(gè)圖表是交互式的,讓你可以自己點(diǎn)擊并探索各個(gè)類(lèi)別。你只需要定義你的所有類(lèi)別,并聲明它們之間的層次結(jié)構(gòu)(見(jiàn)以下代碼中的 parents 參數(shù))并分配對(duì)應(yīng)的值即可,這在我們案例中即為 group by 語(yǔ)句的輸出。
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)在我們向這個(gè)層次結(jié)構(gòu)再添加一層:

為此,我們?cè)偬砑恿硪粋€(gè)涉及三個(gè)類(lèi)別變量的 group by 語(yǔ)句的值。
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()
平行類(lèi)別
另一種探索類(lèi)別變量之間關(guān)系的方法是以下這種流程圖。你可以隨時(shí)拖放、高亮和瀏覽值,非常適合演示時(shí)使用。

代碼如下:
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()
平行坐標(biāo)圖
平行坐標(biāo)圖是上面的圖表的連續(xù)版本。這里,每一根弦都代表單個(gè)觀察。這是一種可用于識(shí)別離群值(遠(yuǎn)離其它數(shù)據(jù)的單條線)、聚類(lèi)、趨勢(shì)和冗余變量(比如如果兩個(gè)變量在每個(gè)觀察上的值都相近,那么它們將位于同一水平線上,表示存在冗余)的好用工具。

代碼如下:
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()
量表圖和指示器

量表圖僅僅是為了好看。在報(bào)告 KPI 等成功指標(biāo)并展示其與你的目標(biāo)的距離時(shí),可以使用這種圖表。
指示器在業(yè)務(wù)和咨詢中非常有用。它們可以通過(guò)文字記號(hào)來(lái)補(bǔ)充視覺(jué)效果,吸引觀眾的注意力并展現(xiàn)你的增長(zhǎng)指標(biāo)。
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)于通過(guò)Plotly實(shí)現(xiàn)交互式數(shù)據(jù)可視化的流程步驟的文章就介紹到這了,更多相關(guān)Plotly交互式數(shù)據(jù)可視化內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python內(nèi)置random模塊生成隨機(jī)數(shù)的方法
這篇文章主要介紹了Python內(nèi)置random模塊生成隨機(jī)數(shù)的方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-05-05
關(guān)于pandas.DataFrame的類(lèi)SQL操作
這篇文章主要介紹了關(guān)于pandas.DataFrame的類(lèi)SQL操作方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,2023-08-08
Python報(bào)錯(cuò)TypeError: ‘dict‘ object is not&
在Python開(kāi)發(fā)的旅程中,報(bào)錯(cuò)信息就像是一個(gè)個(gè)路障,阻礙著我們前進(jìn)的步伐,而“TypeError: ‘dict’ object is not iterable”這個(gè)報(bào)錯(cuò),常常讓開(kāi)發(fā)者們陷入困惑,那么,這個(gè)報(bào)錯(cuò)究竟是怎么產(chǎn)生的呢?又該如何有效地解決它呢?讓我們一起深入探討,找到解決問(wèn)題的方法2024-10-10
剛學(xué)完怎么用Python實(shí)現(xiàn)定時(shí)任務(wù),轉(zhuǎn)頭就跑去撩妹!
朋友問(wèn)我有沒(méi)有定時(shí)任務(wù)的模塊,并且越簡(jiǎn)單越好.剛好前今天就研究了一下定時(shí)任務(wù)模塊,于是就告訴他使用方式,令我沒(méi)有想到的是,這貨他學(xué)會(huì)了之后,居然買(mǎi)了一個(gè)服務(wù)器給女朋友發(fā)消息,發(fā)消息,發(fā)消息……重要的事情說(shuō)三遍,需要的朋友可以參考下2021-06-06
python模擬點(diǎn)擊網(wǎng)頁(yè)按鈕實(shí)現(xiàn)方法
在本篇文章里小編給大家整理的是一篇關(guān)于python模擬點(diǎn)擊網(wǎng)頁(yè)按鈕實(shí)現(xiàn)方法,需要的朋友們可以參考下。2020-02-02
django框架如何集成celery進(jìn)行開(kāi)發(fā)
本文給大家詳細(xì)講解了在django框架中如何集成celery進(jìn)行開(kāi)發(fā),步驟非常詳細(xì),有需要的小伙伴可以參考下2017-05-05
Anaconda虛擬環(huán)境中安裝cudatoolkit和cudnn包并配置tensorflow-gpu的教程
這篇文章詳細(xì)介紹了如何在Anaconda虛擬環(huán)境中配置PyTorch和TensorFlow-GPU,并提供了詳細(xì)的步驟和注意事項(xiàng),通過(guò)圖文講解的非常詳細(xì),需要的朋友可以參考下2025-02-02

