Plotly 與 Plotly Figure

Python 的 Plotly 資料視覺化入門

Alex Scriven

Data Scientist

什麼是 Plotly?

 

  • JavaScript 繪圖函式庫
    • 不用擔心——不需要會 JavaScript!
  • Plotly 提供 Python 封裝

 

Plotly 標誌

Python 的 Plotly 資料視覺化入門

為什麼用 Plotly?

 

Plotly 的優勢:

  • 速度快、易上手
  • plotly.express 低程式碼、低門檻
  • (需要時)高度可自訂
  • 內建互動功能
Python 的 Plotly 資料視覺化入門

建立 Plotly 圖表

 

建立 Plotly 圖表的方式:

  1. plotly.express 快速繪圖(縮寫 px
  2. plotly.graph_objectsgo)獲得更高自訂性

$$

📈 我們多數時間會使用 px

Python 的 Plotly 資料視覺化入門

文件很重要

把關鍵文件連結收好!

  1. 互動式文件

  2. 詳細參考頁:各圖表專屬說明

$$

關於散佈圖:

Python 的 Plotly 資料視覺化入門

建立圖表物件(Figure)

  基本的 plotly 圖表:

import plotly.express as px

days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] temperatures = [28, 27, 25, 31, 32, 35, 36]
fig = px.bar( x=days, y=temperatures, title="Temperatures of the week")
fig.show()
Python 的 Plotly 資料視覺化入門

圖表呈現

每週氣溫的長條圖

Python 的 Plotly 資料視覺化入門

Plotly 图表物件結構

 

Plotly Figure 的組成:

  • layout:控制圖表樣式的字典
    • 每個圖表一個 layout
  • data:設定圖形型態與資料的字典清單
    • 資料+型態=trace,類型超過 40 種!
    • 一張圖可包含多個 trace
  • frames:用於動畫圖(本課不涵蓋)
Python 的 Plotly 資料視覺化入門

一窺 Plotly Figure 內部

 

print(fig)
Figure({'data': [{'type': 'bar',
              'x': array(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'
              , 'Saturday','Sunday'], dtype=object),
              'y': {'bdata': 'HBsZHyAjJA==....'}],
    'layout': {'title': {'text': 'Temperatures of the week'}}})
Python 的 Plotly 資料視覺化入門

Plotly 的即時互動性

$$

  • 對資料點滑鼠懸停查看細節
  • 額外的互動按鈕

滑鼠懸停選項

Python 的 Plotly 資料視覺化入門

一起來練習吧!

Python 的 Plotly 資料視覺化入門

Preparing Video For Download...